|
1 | 1 | class Solution {
|
2 | 2 | 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++; |
16 | 11 | }
|
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); |
18 | 24 | }
|
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++; |
24 | 45 | }
|
25 | 46 | }
|
26 |
| - return sb.toString(); |
| 47 | + return sb; |
27 | 48 | }
|
28 | 49 | }
|
0 commit comments