Given an input string, reverse the string word by word.

For example,
Given s = “the sky is blue“,
return “blue is sky the“.

Clarification:

  1. What constitutes a word?
    A sequence of non-space characters constitutes a word.
  2. Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  3. How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.

这个题目很简单,主要是要注意处理空格。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public String reverseWords(String s) {
if (s == null || s.length() == 0)
return s;
String[] strs = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = strs.length - 1; i >= 0; i--) {
if (strs[i].length() != 0) {
sb.append(strs[i]);
sb.append(" ");
}
}
return sb.toString().trim();
}