class Solution {
public:
    string reverseWords(string s) {
        int size = s.size();
        int i = 0,j = 0;
        while(i < size)
        {
            //skip spaces
            while(i < size && s[i] == ' ')
                i++;
            if(i < size && j > 0)
                s[j++] = ' ';
            int start = j;
            while(i < size && s[i] != ' ')
                s[j++] = s[i++];
            
            reverse(s.begin() + start,s.begin() + j);
        }
        s.resize(j);
        reverse(s.begin(),s.end());
        return s;
    }
};

运行效率:

Runtime: 0 ms, faster than 100.00% of C++ online submissions for Reverse Words in a String.
Memory Usage: 7 MB, less than 78.09% of C++ online submissions for Reverse Words in a String.

思路还是比较巧妙,首先按照顺序逆序每个单词,这个时候有两个指针,一个指针i从前向后遍历,另一个指针j,代表处理后写入的位置。