Skip to content

Commit 1e8651b

Browse files
authored
Update Reverse Words in a String.java
1 parent a996e3b commit 1e8651b

File tree

1 file changed

+41
-20
lines changed

1 file changed

+41
-20
lines changed

Medium/Reverse Words in a String.java

+41-20
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,49 @@
11
class Solution {
22
public String reverseWords(String s) {
3-
Stack<String> stack = new Stack<>();
4-
StringBuilder sb = new StringBuilder();
5-
int idx = 0;
6-
int n = s.length();
7-
while (idx < n) {
8-
if (s.charAt(idx) != ' ') {
9-
sb.append(s.charAt(idx));
10-
}
11-
if (s.charAt(idx) == ' ' || idx == n - 1) {
12-
if (sb.length() > 0) {
13-
stack.push(sb.toString());
14-
sb.setLength(0);
15-
}
3+
StringBuilder sb = trimSpace(s);
4+
reverse(sb, 0, sb.length() - 1);
5+
int start = 0;
6+
int end = 0;
7+
int n = sb.length();
8+
while (start < n) {
9+
while (end < n && sb.charAt(end) != ' ') {
10+
end++;
1611
}
17-
idx++;
12+
reverse(sb, start, end - 1);
13+
start = end + 1;
14+
end++;
15+
}
16+
return sb.toString();
17+
}
18+
19+
private void reverse(StringBuilder sb, int start, int end) {
20+
while (start <= end) {
21+
char temp = sb.charAt(start);
22+
sb.setCharAt(start++, sb.charAt(end));
23+
sb.setCharAt(end--, temp);
1824
}
19-
sb.setLength(0);
20-
while (!stack.isEmpty()) {
21-
sb.append(stack.pop());
22-
if (!stack.isEmpty()) {
23-
sb.append(" ");
25+
}
26+
27+
private StringBuilder trimSpace(String s) {
28+
StringBuilder sb = new StringBuilder();
29+
int start = 0;
30+
int end = s.length() - 1;
31+
while (start <= end && s.charAt(start) == ' ') {
32+
start++;
33+
}
34+
while (end >= start && s.charAt(end) == ' ') {
35+
end--;
36+
}
37+
while (start <= end) {
38+
if (s.charAt(start) != ' ') {
39+
sb.append(s.charAt(start++));
40+
} else {
41+
if (sb.charAt(sb.length() - 1) != ' ') {
42+
sb.append(s.charAt(start));
43+
}
44+
start++;
2445
}
2546
}
26-
return sb.toString();
47+
return sb;
2748
}
2849
}

0 commit comments

Comments
 (0)