变量简洁正确完整思路
left来到一个字符,right来到最后一个字符,如果s[left]不是空格就word+=s[left],遇到空格将单词push_back到双端队列deque ans1,string ans从ans1前部取单词+=并加空格,ans1空了就不要加空格 精确定义 left right ans1 ans wordclass Solution { public: string reverseWords(string s) { int n=s.size(); int left=0,right=n-1; while(left<n&&s[left]==' ')left++; while(right>=0&&s[right]==' ')right--; deque<string>ans1; while(left<=right){ //cout<<s[left]<<' '<<s[right]<<endl; string word; while(s[left]!=' '&&left<=right){ word+=s[left]; left++; } if(word.size()>0)ans1.push_front(word); left++; } string ans; for(auto str:ans1){ ans+=str; ans+=' '; } ans.pop_back(); return ans; } };
class Solution { public: string reverseWords(string s) { int n=s.size(); int left=0,right=n-1; while(left<n&&s[left]==' ')left++; while(right>=0&&s[right]==' ')right--; deque<string>ans1; while(left<=right){ //cout<<s[left]<<' '<<s[right]<<endl; string word; while(s[left]!=' '&&left<=right){ word+=s[left]; left++; } if(word.size()>0)ans1.push_front(word); left++; } string ans; for(auto str:ans1){ ans+=str; ans+=' '; } ans.pop_back(); return ans; } };
踩过的坑 这种类型题考察的是debug能力,cout什么是最恰当的?s[left]比left好,积累 if(word.size()>0)ans1.push_front(word);遇到空格,word都没有积累 while(s[left]!=' '&&left<=right){溢出了