Reverse Words in a String II

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

翻转一个string, 但是里面单词不翻转.

三步:

  1. 翻转整个string
  2. 用left记录每个单词开始的地方, 然后扫到空格就翻转一下.
  3. 最后记得翻转一下最后的string
public void reverseWords(char[] s) {
        reverse(s,0,s.length-1);
        int left = 0;
        for(int i = 0 ; i < s.length; i++) {
            if(s[i] == ' '){
                reverse(s, left, i-1);
                left = i+1;
            }
        }
        reverse(s, left, s.length-1);
    }
    public void reverse (char[] s, int i, int j) {
        while(i < j) {
            char t = s[i];
            s[i] = s[j];
            s[j] = t;
            i++;
            j--;
        }
    }