class Solution {
public void reverseStr(char[] s, int l, int r) {
while(l < r) {
char temp = s[l];
s[l++] = s[r];
s[r--] = temp;
}
}
public String reverseWords(String s) {
char[] str = s.toCharArray();
int n = str.length;
reverseStr(str, 0 , n - 1);
int slow = 0;
int fast = 0;
while(fast < n) {
// skip whitespace
while(fast < n && str[fast] == ' ') fast++;
// add whitespace
if(slow > 0 && fast < n) str[slow++] = ' ';
int start = slow;
// move word to correct place
while(fast < n && str[fast] != ' ') str[slow++] = str[fast++];
// reverse each word
reverseStr(str, start, slow-1);
}
// strim useless space
return new String(str).substring(0, slow);
}
}