In place O(1) solution in C++


  • 0
    R
    class Solution{
    public:
        void reverseWords(string &s) {
            int i=0, len=s.size(), start=0, end=0, ind=0;
            reverse(s, 0, len-1);
            while(i<len){
                if(s[i]==' ') i++;
                else {
                    start=i;
                    while(i<len && s[i]!=' '){
                        end=i++;
                    }
                    reverse(s, start, end);
                    for(int j=start; j<=end; ++j){
                        s[ind++]=s[j]; 
                    }
                    s[ind]=' ';
                    ind++;
                }
            }
            if(s[ind-1]==' ') ind--;
            s.resize(ind);
        }
    private:
        void reverse(string& word, int s, int e){
            while(s<e)
                swap(word[s++],word[e--]);
        }    
    };

Log in to reply
 

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