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.
- What constitutes a word?
A sequence of non-space characters constitutes a word. - Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces. - How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
class Solution {
public:
/*algorithm
reverse whole sentence
reverse word by word
time O(n) space O(1)
*/
void reverse(string &s,int start,int len){
int i = 0,j = len-1;
while(i < j){
swap(s[start+i],s[start+j]);
i++,j--;
}
}
void reverseWords(string &s) {
//space pre-process,remove leading and trailing spaces,reduce words space to 1
int k = 0;
for(int i = 0;i < s.size();i++){
if(s[i] != ' '){
if(i&&s[i-1]==' '&&k)s[k++] = ' ';
s[k++] = s[i];
}
}
s.resize(k);
reverse(s,0,s.size());
for(int i = 0;i < s.size();){
int j = i;
while(j+1 < s.size() && s[j+1] != ' ')++j;
reverse(s,i,j-i+1);
i = j+2;
}
}
};