public class Solution {
public void reverseWords(char[] s) {
if (s == null) return;
int len = s.length;
// 1, reverse the whole sentence
reverse(s, 0, len - 1);
int pre = 0;
// 2, reverse each word
for (int i = 0; i < len; i++) {
if (s[i] == ' ') {
reverse(s, pre, i - 1);
pre = i + 1;
}
}
// 3, reverse the last word, if there is only one word this will solve the corner case
reverse(s, pre, len - 1);
}
private void reverse(char[] s, int i, int j) {
while (i < j) {
char temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
}
}