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.

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?


    public void reverseWords(char[] s) {
        reverse(s, 0, s.length - 1);
        int left = 0, right = 0;
        while(right < s.length){
            if(s[right] == ' '){
                reverse(s, left, right - 1);
                left = ++ right;
            }else right ++;
        }
        reverse(s, left, right - 1);
    }

    private void reverse(char[] s, int start, int end){
        int i = start, j = end;
        while(i < j){
            char tmp = s[i];
            s[i] = s[j];
            s[j] = tmp;
            i ++;
            j --;
        }
    }

results matching ""

    No results matching ""