My C++ solutions


  • 0
    H
    void reverse(string &s,int i,int j){
        while(j>i){
            char t=s[i];
            s[i++]=s[j];
            s[j--]=t;
        }
    }
    

    public:
    void reverseWords(string &s) {

        s.erase(0, s.find_first_not_of("\r\t\n ")); 
        s.erase(s.find_last_not_of("\r\t\n ") + 1);
        int start=0;
        int i=0;
        string m;
        if(s.size()==1||s.size()==0) return;
        for(int i=0;i<=s.size()-1;++i){
            if(s[i]==' '&&s[i+1]==' ')  continue;
            else m.push_back(s[i]);
        }
        
        i=0;    
        while(m[i]!=0){
            if(m[i]!=' ')   ++i;
            else{
                reverse(m,start,i-1);
                start=++i;
            }
        }
        reverse(m,start,m.size()-1);
        reverse(m,0,m.size()-1);
        
        s=m;
    

    }
    };


Log in to reply
 

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