Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Clarification:
- 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: void reverse(string &s, int begin, int end){ int p=begin; int q=end-1; while(p < q){ char tmp = s[p]; s[p++]=s[q]; s[q--]=tmp; } } void reverseWords(string &s) { if( s.size()==0){ return; } int index=0,tmp=index; while(tmp<s.size()){ while(tmp<s.size() && s[tmp]==' '){ tmp++; } while(tmp<s.size() && s[tmp]!=' '){ s[index++]=s[tmp++]; } if(tmp<s.size()){ s[index++]=' '; tmp++; } } if(index ==0 ){ s=""; return; } if(s[index-1]==' '){ index--; } s.erase(index,s.size()-index); reverse(s,0,index); int begin=0,end=0; while(end<s.size()){ begin=end; while(end<s.size() && s[end]!=' '){ end++; } reverse(s,begin,end); end++; } } };