Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
思路:首先将原来string split成 string array,然后倒着再连接起来。
注意: 用stringbuilder,avoid create so many string in connection.
class Solution {
public String reverseWords(String s) {
if(s == null || s.length() == 0) {
return s;
}
s = s.trim();
String[] splits = s.split(" ");
StringBuilder sb = new StringBuilder();
for(int i = splits.length - 1; i > 0; i--) {
if(!splits[i].isEmpty()) {
sb.append(splits[i]).append(" ");
}
}
if(!splits[0].isEmpty()) {
sb.append(splits[0]);
}
return sb.toString();
}
}