My simple C++ solution, 8ms


  • 0
    Z
    class Solution {
    public:
        void reverseWords(string &s) {
            
            int start=0;
            while(start<s.size() && s.at(start)==' ') start++;
            s=s.substr(start,s.size()-start);//remove the leading spaces
            
            int n=s.size();
            string res="";
            int len=0;
            for(int i=n-1;i>=0;i--){
                if(s.at(i)!=' ') len++;
                if(len>0 && s.at(i)==' '){
                    res+=s.substr(i+1,len);
                    res+=" ";
                    len=0;
                }
            }
            res+=s.substr(0,len);
            s=res;
        }
    };

Log in to reply
 

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