双指针算法
(双指针) $O(n)$
C++ 代码
class Solution {
public:
string reverseWords(string s) {
string ans;
for(int i = 0; i < s.size(); i ++)
{
if(s[i] == ' ') continue;
int j = i;
while(j < s.size() && s[j] != ' ') j ++;
if(ans.size()) ans = " " + ans;
ans = s.substr(i, j - i) + ans;
i = j;
}
return ans;
}
};