|
2 | 2 |
|
3 | 3 | /**
|
4 | 4 | * 186. Reverse Words in a String II
|
5 |
| - * |
6 |
| - * Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters. |
| 5 | +
|
| 6 | + Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters. |
7 | 7 |
|
8 | 8 | The input string does not contain leading or trailing spaces and the words are always separated by a single space.
|
9 | 9 |
|
|
14 | 14 | Could you do it in-place without allocating extra space?
|
15 | 15 | */
|
16 | 16 | public class _186 {
|
17 |
| - |
| 17 | + public static class Solution1 { |
18 | 18 | public void reverseWords(char[] s) {
|
19 |
| - // Three steps to reverse |
20 |
| - // 1, reverse the whole sentence |
21 |
| - reverse(s, 0, s.length - 1); |
22 |
| - // 2, reverse each word |
23 |
| - int start = 0; |
24 |
| - for (int i = 0; i < s.length; i++) { |
25 |
| - if (s[i] == ' ') { |
26 |
| - reverse(s, start, i - 1); |
27 |
| - start = i + 1; |
28 |
| - } |
| 19 | + // Three steps to reverse |
| 20 | + // 1, reverse the whole sentence |
| 21 | + reverse(s, 0, s.length - 1); |
| 22 | + // 2, reverse each word |
| 23 | + int start = 0; |
| 24 | + for (int i = 0; i < s.length; i++) { |
| 25 | + if (s[i] == ' ') { |
| 26 | + reverse(s, start, i - 1); |
| 27 | + start = i + 1; |
29 | 28 | }
|
30 |
| - // 3, reverse the last word, if there is only one word this will solve the corner case |
31 |
| - reverse(s, start, s.length - 1); |
| 29 | + } |
| 30 | + // 3, reverse the last word, if there is only one word this will solve the corner case |
| 31 | + reverse(s, start, s.length - 1); |
32 | 32 | }
|
33 | 33 |
|
34 | 34 | private void reverse(char[] s, int start, int end) {
|
35 |
| - while (start < end) { |
36 |
| - char temp = s[start]; |
37 |
| - s[start++] = s[end]; |
38 |
| - s[end--] = temp; |
39 |
| - } |
| 35 | + while (start < end) { |
| 36 | + char temp = s[start]; |
| 37 | + s[start++] = s[end]; |
| 38 | + s[end--] = temp; |
| 39 | + } |
40 | 40 | }
|
| 41 | + } |
41 | 42 |
|
42 | 43 | }
|
0 commit comments