Solution:
1. reversed the whole string
2. reversed each word in the reversed string.
3. remove multiple space between words.
Code:
class Solution {
public:
void reverseWords(string &s) {
if(s.empty()) return;
int head = 0;
int end = s.length() -1;
char temp;
//reverse the string
while(head<end){
temp = s[head];
s[head]= s[end];
s[end] = temp;
head++;
end --;
}
head = 0;
int temp_end;
//reverse each word in the reversed string
while(true){
while(head < s.length() && s[head] == ' '){
head++;
}
if(head >= s.length()) break;
end = head;
while(end < s.length() && s[end] != ' '){
end++;
}
end --;
temp_end = end;
while(head<end){
temp = s[head];
s[head] = s[end];
s[end] = temp;
head++;
end--;
}
head = temp_end + 1;
}
int cur = 0;
head = 0;
//reduce multiple " " between word.
while(head<s.length()){
if(s[head] != ' '){//move word to s[cur]. This step ensures that there are no multiple //spaces between words.
s[cur++] = s[head++];
}
else{//if we meet a " " at s[head],first find the next word
while(head < s.length() && s[head] == ' '){
head++;
}
if(head >= s.length()) break;
if(cur > 0){//if cur > 0, first append a " " at s[cur]. then append the word
s[cur] = ' ';
cur++;
}
}
}
s = s.substr(0,cur);
}
};