-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathDay-15 Reverse Words in a String
More file actions
39 lines (34 loc) · 1017 Bytes
/
Day-15 Reverse Words in a String
File metadata and controls
39 lines (34 loc) · 1017 Bytes
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
34
35
36
37
38
39
class Solution {
public String reverseWords(String s) {
// remove leading spaces
s = s.trim();
// split by multiple spaces
List<String> wordList = Arrays.asList(s.split("\\s+"));
Collections.reverse(wordList);
return String.join(" ", wordList);
}
}
class Solution {
public String reverseWords(String s) {
int left = 0, right = s.length() - 1;
// remove leading spaces
while (left <= right && s.charAt(left) == ' ') ++left;
// remove trailing spaces
while (left <= right && s.charAt(right) == ' ') --right;
Deque<String> d = new ArrayDeque();
StringBuilder word = new StringBuilder();
// push word by word in front of deque
while (left <= right) {
char c = s.charAt(left);
if ((word.length() != 0) && (c == ' ')) {
d.offerFirst(word.toString());
word.setLength(0);
} else if (c != ' ') {
word.append(c);
}
++left;
}
d.offerFirst(word.toString());
return String.join(" ", d);
}
}