【LeetCode】557. Reverse Words in a String III

Difficulty: Easy

 More:【目錄】LeetCode Java實現html

Description

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.java

Example 1:post

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

 

Note: In the string, each word is separated by single space and there will not be any extra space in the string.ui

Intuition

Find the start and end of each word, then reverse each word.spa

Solution

    public String reverseWords(String s) {
        if(s==null || s.length()==0)
            return s;
        StringBuilder sb = new StringBuilder(s);
        int start=0;
        int end=0;
        while(start<s.length()){
            while(end<s.length() && s.charAt(end)!=' ')
                end++;
            reverse(sb,start,end-1);
            end++;
            start=end;
        }
        return sb.toString();
    }
    
    private void reverse(StringBuilder sb,int start,int end){
        while(start<end){
            char temp=sb.charAt(start);
            sb.setCharAt(start,sb.charAt(end));
            sb.setCharAt(end,temp);
            start++;
            end--;
        }
    }

  

Complexity

Time complexity : O(n)htm

Space complexity :  O(1)blog

What I've learned

1. Learn how to get the start and end of each word.ip

 

 More:【目錄】LeetCode Java實現get

相關文章
相關標籤/搜索