Description:
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",return "blue is sky the".
思路:
代码:
public class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0) {
return s;
}
int len = s.length(),end = len;
StringBuilder result = new StringBuilder();
for (int i = len - 1; i >= 0; i--) {
if (s.charAt(i) == ' ') {
end = i;
} else if (i == 0 || s.charAt(i-1) == ' ') {
if (result.length() != 0) {
result.append(' ');
}
result.append(s.substring(i, end));
}
}
return result.toString();
}
}
网友评论