Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
Subscribe to see which companies asked this question
class Solution {
public:
void reverseWords(string &s) {
reverse(s.begin(),s.end());
int before=0;
//int end=0;
for(int i=0;i<s.size();i++){
if(s[i]==' '){
while(s[i+1]==' '){
s.erase(s.begin()+i+1);
}
reverse(s.begin()+before,s.begin()+i);
before=i+1;
//end=i;
}
}
reverse(s.begin()+before,s.end());
int j=0;
while(s[j]==' '){
s.erase(s.begin()+j);
//j++;
}
int end=s.size();
while(s[end-1]==' '){
s.erase(s.begin()+end-1);
}
if(s[end-1]==' '){
s.erase(s.begin()+end);
}
}
};