先整体翻转,再对每个单词翻转
C++ 代码
class Solution {
public:
string reverseWords(string s) {
reverse(s.begin(), s.end());
int cur = 0;
for(int i = 0; i < s.size(); ++ i){
if(s[i] == ' '){
reverse(s.begin() + cur, s.begin() + i);
cur = i + 1;
}
}
reverse(s.begin() + cur, s.end());
return s;
}
};