[LeetCode] 186. Reverse Words in a String II

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

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

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

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

Two Pointer

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

思路

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

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.word

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;
    }
}
相關文章
相關標籤/搜索