Saturday, March 8, 2014

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

很简单一个题目
把答案贴出来,赞一个,一次性通过
public String reverseWords(String s) {
String res = "";
ArrayList<String> al = new ArrayList<String>();
if(s==null||s.length()==0) return res;
for(int i=0; i<s.length(); i++){
if(s.charAt(i)==' ') continue;
int start = i;
while(i<s.length() && s.charAt(i)!=' ')
i++;
al.add(0, s.substring(start, i));
}
for(int i=0; i<al.size(); i++){
res += al.get(i);
res += " ";
}
if(res.length()>0)
return res.substring(0, res.length()-1);
else
return res;
}
view raw gistfile1.java hosted with ❤ by GitHub

No comments:

Post a Comment