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?

Two Pointer

Time Complexity O(N)
Space Complexity O(1)

思路

Step1 : reverse the whole char of string word by word.

the sky is blue -> eulb si yks eht

Step2: reverse the characters word by word, use two pointer, left is the start of the word and right keep track of the word which is not a space, when it reaches a space, then reverse the word from left to right - 1.

eulb si yks eht
l   r

代码

public void reverseWords(char[] str) {
    //reverse the whole str
    reverse(str, 0, str.length - 1);
    int r = 0;
    while(r < str.length){
        int l = r;
        while(r < str.length && str[r] != ' '){
            r++;
        }
        reverse(str, l, r - 1);
        r++;
    }
}

private void reverse(char[] str, int left, int right){
    while(left < right){
        char temp = str[left];
        str[left++] = str[right];
        str[right--] = temp;
    }
}

annielulu
5 声望5 粉丝