151.Reverse Words in a String

Test cases

1
" " // expect ""

Solution 1: accepted 20ms

Time: O(n)
Space: O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public String reverseWords(String s) {
StringBuilder sb = new StringBuilder();
String temp = "";
for (int i = s.length() - 1; i >= 0; i--) {
char cur = s.charAt(i);
if (cur == ' ' && temp.length() != 0) {
sb.append(temp + " ");
temp = "";
} else if (cur == ' ') {
continue;
} else {
temp = cur + temp;
}
}
sb.append(temp);
return sb.toString().trim();
}

Solution 2: accepted 12ms

Time: O(n)
Space: O(n)

1
2
3
4
5
6
7
8
public String reverseWords(String s) {
String[] words = s.trim().split("\\s+");
StringBuilder sb = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
sb.append(words[i] + " ");
}
return sb.deleteCharAt(sb.length() - 1).toString();
}