My C++ solution


  • 0
    M

    Reverse the whole string, then reverse each word separated by ' '.

    class Solution {
    public:
        void reverseWords(string &s) {
            reverse(s.begin(), s.end());
            int m = 0;
            for (int i = 0 ; i < s.size(); i++) {
                if (s[i] == ' ') {
                    reverse(s.begin() + m, s.begin() + i);
                    m = i + 1;
                }
            }
            reverse(s.begin() + m, s.end());
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.