Skip to content

Commit 60b74f4

Browse files
add a solution for 186
1 parent 99e0525 commit 60b74f4

File tree

1 file changed

+46
-34
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+46
-34
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,55 @@
11
package com.fishercoder.solutions;
22

3-
/**
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.
7-
8-
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
9-
10-
For example,
11-
Given s = "the sky is blue",
12-
return "blue is sky the".
13-
14-
Could you do it in-place without allocating extra space?
15-
*/
163
public class _186 {
17-
public static class Solution1 {
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;
4+
public static class Solution1 {
5+
public void reverseWords(char[] s) {
6+
// Three steps to reverse
7+
// 1, reverse the whole sentence
8+
reverse(s, 0, s.length - 1);
9+
// 2, reverse each word
10+
int start = 0;
11+
for (int i = 0; i < s.length; i++) {
12+
if (s[i] == ' ') {
13+
reverse(s, start, i - 1);
14+
start = i + 1;
15+
}
16+
}
17+
// 3, reverse the last word, if there is only one word this will solve the corner case
18+
reverse(s, start, s.length - 1);
19+
}
20+
21+
private void reverse(char[] s, int start, int end) {
22+
while (start < end) {
23+
char temp = s[start];
24+
s[start++] = s[end];
25+
s[end--] = temp;
26+
}
2827
}
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);
3228
}
3329

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-
}
30+
public static class Solution2 {
31+
public void reverseWords(char[] s) {
32+
reverse(s, 0, s.length);
33+
for (int i = 0; i < s.length; i++) {
34+
int start = i;
35+
while (i < s.length && s[i] != ' ') {
36+
i++;
37+
}
38+
reverse(s, start, i);
39+
}
40+
}
41+
42+
private void reverse(char[] chars, int start, int end) {
43+
int left = start;
44+
int right = end - 1;
45+
while (left < right) {
46+
char tmp = chars[left];
47+
chars[left] = chars[right];
48+
chars[right] = tmp;
49+
left++;
50+
right--;
51+
}
52+
}
4053
}
41-
}
4254

4355
}

0 commit comments

Comments
 (0)