这个题比较简单,代码也很少。
方法1:字符串缓存
class Solution { public: string ReverseSentence(string str) { string res; string tmp; for(int i=0;i<str.length();i++){ char c = str[i]; if(c != ' '){ tmp = tmp + c; }else{ res = ' ' + tmp + res; tmp = ""; } } return tmp + res; } };方法2:使用栈缓存
string ReverseSentence(string str) { string res; stack<char> data; for(int i=0;i<str.length();i++){ char c = str[i]; if(c != ' '){ data.push(c); }else{ while(!data.empty()){ res = data.top() + res; data.pop(); } res = ' ' + res; } } while(!data.empty()){ res = data.top() + res; data.pop(); } return res; }