Given an input string, reverse the string word by word.
For example,
Given s = "
return "
Given s = "
the sky is blue
",return "
blue is sky the
".
很简单一个题目
把答案贴出来,赞一个,一次性通过
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
No comments:
Post a Comment