[leedcode 151] 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) {
        //利用java中StringBuilder的insert(0,String)函数,注意第一个字符是空格的情况
        //因此需要检查word的长度
        if(s==null||s.length()<=0) return s;
        StringBuilder word=new StringBuilder();
        StringBuilder res=new StringBuilder();
        for(int i=0;i<s.length();i++){
            if(s.charAt(i)!=' ') word.append(s.charAt(i));
            else if(s.charAt(i)==' '){
                if(word.length()>0){
                    res.insert(0,word+" ");
                    word=new StringBuilder();
                }else{
                    continue;
                }
            }
        }
        if(word.length()>0) res.insert(0,word+" ");
        return res.toString().trim();
    }
}

 

posted @ 2015-08-01 21:38  ~每天进步一点点~  阅读(124)  评论(0编辑  收藏  举报