186. Reverse Words in a String II

Link

Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.

The input string does not contain leading or trailing spaces and the words are always separated by a single space.

For example, Given s = "the sky is blue", return "blue is sky the".

Could you do it in-place without allocating extra space?

Solution

    public String reverseWords(char[] s) {
        int n = s.length;
        reverse(s, 0, n-1);
        int i = 0, j = 0;
        while( i < n){
            while(i < j || i < n && s[i] == ' ') i++;
            while(j < i || j < n && s[j] != ' ') j++;
            reverse(s, i, j-1);
        }
        return new String(s);
    }

    public void reverse(char[] s, int from, int end){
        char temp = ' ';
        while(from < end){
            temp = s[from];
            s[from] = s[end];
            s[end] = temp;
            from++;
            end--;
        }
    }

Last updated

Was this helpful?