Reverse Words in a String

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

思路:

  这个题目很简单,主要注意两个个corner case:1、s前后有空白符 2、s 中间分隔符是一个或者多个空白字符 所以split.(" +")而不是split(" ")

我的代码:

public class Solution {
    public String reverseWords(String s) {
        if(s == null || s.length() == 0)    return s;
        s = s.trim();
        StringBuffer part = new StringBuffer();
        String rst = "";
        for(int i = 0; i < s.length(); i++)
        {
            if(s.charAt(i) == ' ')
            {
                String tmp = part.toString();
                if(tmp == null || tmp.equals(""))   continue;
                else
                {
                    rst  = " " + part.toString() + rst;
                    part = new StringBuffer();
                }
            }
            else
            {
                part.append(s.charAt(i));
            }
        }
        rst = part.toString()+rst; 
        return rst;
    }
}
View Code

他人代码:

public class Solution {
    public String reverseWords(String s) {
        s = s.trim();
        String[] words = s.split(" +");
        StringBuilder str = new StringBuilder();

        if (words.length != 0) {
            for (int i = words.length - 1; i > 0; i--) {
                str.append(words[i] + " ");
            }
            str.append(words[0]);
        }

        return str.toString();

    }
}
View Code

 

posted on 2015-03-22 11:04  zhouzhou0615  阅读(105)  评论(0编辑  收藏  举报

导航