Skip to content

Commit f626d03

Browse files
authored
Update Reverse words in a String III.java
1 parent d202d37 commit f626d03

File tree

1 file changed

+27
-20
lines changed

1 file changed

+27
-20
lines changed
Lines changed: 27 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,30 @@
11
class Solution {
2-
public String reverseWords(String s) {
3-
int idx = 0;
4-
int n = s.length();
5-
StringBuilder sb = new StringBuilder();
6-
int start = 0;
7-
while (idx < n) {
8-
while (idx < n && s.charAt(idx) != ' ') {
9-
idx++;
10-
}
11-
int curr = idx - 1;
12-
while (curr >= start) {
13-
sb.append(s.charAt(curr--));
14-
}
15-
if (idx != n) {
16-
sb.append(" ");
17-
}
18-
idx++;
19-
start = idx;
2+
public String reverseWords(String s) {
3+
int start = 0;
4+
int end = 0;
5+
char[] chars = s.toCharArray();
6+
while (end < s.length()) {
7+
if (chars[end] == ' ') {
8+
if (start < end - 1) {
9+
reverse(chars, start, end - 1);
10+
}
11+
end++;
12+
start = end;
13+
} else {
14+
end++;
15+
}
16+
}
17+
if (start < end) {
18+
reverse(chars, start, end - 1);
19+
}
20+
return String.valueOf(chars);
21+
}
22+
23+
private void reverse(char[] chars, int start, int end) {
24+
while (start < end) {
25+
char temp = chars[start];
26+
chars[start++] = chars[end];
27+
chars[end--] = temp;
28+
}
2029
}
21-
return sb.toString();
22-
}
2330
}

0 commit comments

Comments
 (0)