Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
思考:一开始没有考虑空格。去掉不合法空格+两次翻转,不需要额外空间。
class Solution { public: void reverseWords(string &s) { int len=s.length(); int i=0,j=len-1; //去掉前后空格 while(i<len&&s[i]==' ') i++; while(j>=0&&s[j]==' ') j--; len=j-i+1; s=s.substr(i,len); //去掉中间空格 for(i=0;i<s.length();i++) { if(s[i]==' ') { j=i+1; while(s[j]==' ') j++; s.erase(i+1,j-i-1); } } len=s.length(); for(i=0;i<len/2;i++) swap(s[i],s[len-i-1]); int start=0; for(i=0;i<=len;i++) { if((i<len&&s[i]==' ')||i==len) { for(j=start;j<(i+start)/2;j++) swap(s[j],s[i-(j-start)-1]); start=i+1; } } } };