1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public String reverseWords(String s) {
Deque<String> words = new ArrayDeque<>();
for (String substring : s.split(" ")) {
if (substring.length() == 0) {
continue;
}
words.offerLast(new StringBuilder(substring).toString());
}
if (words.isEmpty()) {
return "";
}
StringBuilder ans = new StringBuilder();
while (!words.isEmpty()) {
ans.append(words.pollLast())
.append(" ");
}
ans.deleteCharAt(ans.length() - 1);
return ans.toString();
}
}

用split就完事儿了. yyds. 和71题simplify path有点儿像.

时间复杂度: O(n)
空间复杂度: O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public String reverseWords(String s) {
int ptr = 0;
Deque<String> words = new ArrayDeque<>();
while (ptr < s.length()) {
// Skip any space
while (ptr < s.length() && s.charAt(ptr) == ' ') {
ptr += 1;
}
// Check if out of bound
if (ptr == s.length()) {
break;
}
// Found non-space char, start building word
StringBuilder currWord = new StringBuilder();
while (ptr < s.length() && s.charAt(ptr) != ' ') {
currWord.append(s.charAt(ptr));
ptr += 1;
}
words.push(currWord.toString());
}
if (words.size() == 0) {
return "";
}
StringBuilder ans = new StringBuilder();
while (!words.isEmpty()) {
ans.append(words.pop())
.append(' ');
}
ans.deleteCharAt(ans.length() - 1);
return ans.toString();
}
}

不使用split的解法. 和atoi那道题很像.

时间复杂度: O(n)
空间复杂度: O(n)

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public String reverseWords(String s) {
String[] words = s.trim().split(" ");
StringBuilder result = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
if (!words[i].isEmpty())
result.append(words[i]).append(" ");
}
return result.toString().trim();
}
}

这个答案更好. trim()这个method学到了.