Given an input string , reverse the string word by word.

1
2
Input:  ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]

Reverse the whole string, then reverse each word.

Use start to mark the start of each string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public void reverseWords(char[] s) {
reverse(s, 0, s.length - 1);

int start = 0;
for (int i = 0; i < s.length; ++i) {
if (s[i] == ' ') {
reverse(s, start, i-1);
start = i + 1;
}
}
reverse(s, start, s.length - 1);
}

public void reverse(char[] s, int start, int end) {
while (start < end) {
char tmp = s[start];
s[start] = s[end];
s[end] = tmp;
start++;
end--;
}
}