An easy and clear way to solve the problem with O(1) space and 12 lines


  • 3
    G
    //reverse the whole string, then erase spaces and reverse the words
    
    void reverseWords(string &s) {
        int top;
        reverse(s.begin(),s.end());   
        for(int i=0;i<s.size();i++){
            top=i;
            while(i<s.size()&&s[i]==' ') i++;  
            s.erase(top,i-top);    
            i=top;
            while(i<s.size()&&s[i]!=' ') i++;    
            reverse(s.begin()+top,s.begin()+i);   
        }
        if(*(s.end()-1)==' ') s.erase(s.end()-1);  
    }

  • 0
    G

    clean nice code, but erase() would trigger a copy of all chars behind. Can you do this without using erase?


Log in to reply
 

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