Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
void reverseWords(string &s) {
int length=s.size();
if(length==0) return ;
int pre=0;
int post=length-1;
while(pre<post){
swap(s[pre],s[post]);
++pre;
--post;
}
int start=0;
int end=0;
while(end<length){
while(end<length&&s[end]!=' '){
end++;
}
pre=start;
post=end-1;
while(pre<post){
//swap(s[pre],s[post]);
char ch=s[pre];
s[pre]=s[post];
s[post]=ch;
++pre;
--post;
}
while(end<length&&s[end]==' '){
end++;
}
start=end;
}
int len=s.size();
int low=0;
int fast=0;
while(fast<len){
if(s[fast]!=' '||((fast+1<len)&&s[fast]==' '&&s[fast+1]!=' '&&low!=0)){
low++;
}
fast++;
s[low]=s[fast];
}
s.resize(low,'\0');