-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathReverse Words in a String II.java
executable file
·111 lines (92 loc) · 2.84 KB
/
Reverse Words in a String II.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
M
1528126762
tags: String
#### In-place reverse
- reverse用两回. 全局reverse。局部:遇到空格reverse
- 注意ending index: `i == str.length - 1`, 结尾点即使没有' '也要给reverse一下最后一个词
```
/*
Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Could you do it in-place without allocating extra space?
Related problem: Rotate Array
Hide Company Tags Amazon Microsoft
Hide Tags String
Hide Similar Problems (M) Reverse Words in a String (E) Rotate Array
*/
/*
//1. reverse all. 2. reverse local with 2 pointer.
//build reverse(start,end)
*/
public class Solution {
public void reverseWords(char[] str) {
if (str == null || str.length <= 1) {
return;
}
reverse(str, 0, str.length - 1);
int start = 0;
for (int i = 0; i < str.length; i++) {
if (str[i] == ' ') {
reverse(str, start, i - 1);
start = i + 1;
} else if (i == str.length - 1) {
reverse(str, start, i);
}
}//end for
}
public void reverse(char[] s, int start, int end) {
while (start < end) {
char temp = s[start];
s[start] = s[end];
s[end] = temp;
start++;
end--;
}
}
}
/*
Thoughts: write an example: reverse the whole thing, then reverse each individual word, split by space.
Note: becase we don't have space at end of the char[], so we will ignore last word. Remember to reverse that one.
*/
public class Solution {
public void reverseWords(char[] s) {
if (s == null || s.length == 0) {
return;
}
int len = s.length;
//reverse whole
for (int i = 0; i < len / 2; i++) {
char temp = s[i];
s[i] = s[len - 1 - i];
s[len - 1 - i] = temp;
}
//reverse partial
int start = 0;
int mid = 0;
int end = 0;
for (int i = 0; i < len; i++) {
if (s[i] == ' ') {
mid = start + (end - start) / 2;
for (int j = start; j <= mid; j++) {
char temp = s[j];
s[j] = s[end - (j - start)];
s[end - (j - start)] = temp;
}
start = i + 1;
} else {
end = i;
}
}
//Process last word
mid = start + (end - start) / 2;
for (int j = start; j <= mid; j++) {
char temp = s[j];
s[j] = s[end - (j - start)];
s[end - (j - start)] = temp;
}
}
}
```