算法
(模拟)
取出每个单词,然后翻转一下即可。
C++ 代码
class Solution {
public:
string reverseWords(string s) {
string word = "", ans = "";
for (auto c : s) {
if (c == ' ') {
if (word != "") {
reverse(word.begin(), word.end());
ans += word;
}
word = "";
ans += c;
}
else word += c;
}
if (word != "") {
reverse(word.begin(), word.end());
ans += word;
}
return ans;
}
};