Reverse Words in a String

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.

 

public class Solution {
    public String reverseWords(String s) {
        if (s.length() == 0) return ""; //边界判断
        StringBuffer sb = new StringBuffer();
        String[] ss = s.split(" ");
        for (int i = ss.length - 1; i >= 0; i--) {
            if (!ss[i].equals("")) { //split会把两个空格符判定为两个分隔符,分割出“”
                sb.append(ss[i]).append(" ");  //sb要用append
            }
        }
        if (sb.length() == 0) return "";   //边界判断,有可能是“ ”
        return sb.substring(0, sb.length() - 1);
    }
}

 

posted @ 2017-06-29 10:42  hafgyyb  阅读(134)  评论(0)    收藏  举报