My 8ms C++ solution


  • 0
    D
    class Solution {
    public:
        void reverseWords(string &s) {
            string r;
            int i = s.size()-1, j = i;
            while( i >= 0 ) {
                if( s[i] != ' ' && s[j] == ' ' ) 
                    j = i;
                else if( s[i] == ' ' && s[j] != ' ' ) {
                    r.append(s.substr(i,j-i+1));
                    j = i;
                }
                i--;
            }
            // if the first char is non-space add a space before it
            if( i == -1 && s[0] != ' ' ) {
                r.push_back(' ');
                r.append(s.substr(0, j+1));
            }
            // because I add heading spaces before each word, so here I need remove any spaces in the head of the whole string
            i = 0;
            while(i < r.size() && r[i] == ' ')
                i++;
            s = r.substr(i,r.size()-i);
        }
    };

Log in to reply
 

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