class Solution {
public String reverseWords(String s) {
// Remove the spaces
String str = removeSpace(s);
char[] words = str.toCharArray();
// Reverse the whole sentence
reverse(words, 0, words.length - 1);
// Reverse each word in the sentence
reverseEachWord(words);
return new String(words);
}
private String removeSpace(String s){
char[] array = s.toCharArray();
int slow = 0;
for(int fast = 0; fast < array.length; fast++){
if(array[fast] == ' ' && (fast == 0 || array[fast - 1] == ' ')){
continue;
}
array[slow++] = array[fast];
}
if(slow > 0 && array[slow - 1] == ' '){
slow--;
}
return new String(array, 0, slow);
}
private void reverse(char[] words, int left, int right){
while(left < right){
char temp = words[right];
words[right] = words[left];
words[left] = temp;
left++;
right--;
}
}
private void reverseEachWord(char[] words){
int begin = 0, end = 0;
for(int i = 0; i < words.length; i++){
if(words[i] != ' ' && (i == 0 || words[i - 1] == ' ')){
begin = i;
}
if(words[i] != ' ' && (i == words.length - 1 || words[i + 1] == ' ')){
end = i;
reverse(words, begin, end);
}
}
}
}