[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(); } }