My c++ code and use no storage space


  • 1
    L
    class Solution {
    public:
        void reverseWords(string &s) {
            int len;
            {
                int cnt=0;
                int i=0;
                bool tell=false;
                while (s[cnt]!='\0'){
                    if (s[cnt]==' '){
                        if (tell) s[i++]=s[cnt],tell=false;
                    }else s[i++]=s[cnt],tell=true;
                    cnt++;
                }
                if (i!=0&&s[i-1]==' ') i--;
                len=i;
                if (cnt-i>0)s.erase(i,cnt-i);
            }
            int st=0;
            for (int i=0;i<=len;i++){
                if (i==len||s[i]==' '){
                    int ed=i-1;
                    while (ed-st>=1){
                        swap(s[ed--],s[st++]);
                    }
                    st=i+1;
                }
            }
            int ed=len-1;st=0;
            while (ed-st>=1){
                swap(s[ed--],s[st++]);
            }
        }
    };
    

    fuck the string erase


Log in to reply
 

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