Given an input string, reverse the string word by word.

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

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

 

倒序字符串。

 

注意使用BufferString,因为如果使用String的话,会多次建立对象,会很慢。

public class Solution {
    public String reverseWords(String s) {
        int len = s.length();
        if( len == 0)
            return s;
        StringBuffer result = new StringBuffer() ;
        int end = len-1,start = 0;
        while( end >= 0 && s.charAt(end) == ' ')
            end--;
        if( end == -1)
            return result.toString();
        while( start < len && s.charAt(start) == ' ')
            start++;
        int pos = end+1;
        for( int i = end ; i >= start ; i-- ){
            if( s.charAt(i) == ' ') {
                result.append(s.substring(i+1,pos));
                result.append(" ");
                while (i < end && s.charAt(i) == ' ')
                    i--;
                i++;
                pos = i;

            }
        }
        result.append(s.substring(start,pos));
        return result.toString();
    }
}