Reverse Words in a String

话说我们昨晚去看了侏罗纪公园,原来xd就是我最爱的巨幕,来美国这么多年了,怀念和小星星一路成长,一路看电影的经历,avatar是我们在美国一起看的第一部电影。老美看完好片子,还喜欢鼓个掌。

 

这题one pass in place就是麻烦,要多做个string来判断单词

要用到sb的insert,不过可以练习一下关于corner case的理解

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.

click to show clarification.

Clarification:

 

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.
public class Solution {
    public String reverseWords(String s) {
        s = s.trim();
        if(s==null ||s.length()<=1) return s;
        StringBuilder sb  = new StringBuilder();
        for(int i = 0;i<s.length();i++){
            if(s.charAt(i)!=' '){
                String word = new String();
                while(i<s.length() && s.charAt(i)!=' '){
                    word = "" + word +  s.charAt(i);
                    i++;
                }
                if(sb.length()!=0){
                    sb.insert(0," ");
                }
                    sb.insert(0,word);
            }
        }
            
           
        return sb.toString();
    }
}

 

posted @ 2015-06-16 01:06  世界到处都是小星星  阅读(157)  评论(0编辑  收藏  举报