class Solution
{
public:
    void reverseWords(string &s)
    {
        if (s.empty())
            return;
        vector<string> words;
        auto p1 = s.begin(), p2 = s.begin(), p3 = s.end();
        while (p2 != p3)
        {
            while (' ' == *p1 && p1 != p3)
            {
                ++p1;
            }
            p2 = p1;
            while (' ' != *p2 && p2 != p3)
                ++p2;
            if (p1 != p3)
                words.push_back(string(p1, p2));
            p1 = p2;
        }
        reverse(words.begin(), words.end());
        s.clear();
        for (int i = 0; i < words.size(); ++i)
        {
            if (1 == words.size())
                s = words[i];
            else if (i == words.size() - 1)
                s += words[i];
            else
                s += words[i] + ' ';
        }
    }
};
