C++简单代码/10行:
class Solution {
public:
string ReverseSentence(string s) {
for(int i = 0; i < s.size() && s[i] == ' ';i ++)
if (i == s.size() - 1 ) return s;
stack<string> stk;
string res,str;
istringstream ss(s);
if (s == " ") return res + " ";
while (ss >> str) stk.push(str), stk.push(" ");
if (!stk.empty()) stk.pop();
while (!stk.empty()) res += stk.top(), stk.pop();
return res;
}
};
京公网安备 11010502036488号