Sharing my 8ms (in-place) C++ solution


  • 0
    T
    class Solution {
    public:
        void reverseWords(string &s) {
            reverse(s.begin(), s.end());
            int n = s.length();
            int start=0, end;
            while(start<n)
            {
                while(start<n && s[start]==' ')
                    start++;
                end = start;
                while(end<n && s[end]!=' ')
                end++;
                reverse(s.begin()+start, s.begin()+end);
                start = end+1;
            }
            
            int count=0;
            int index=0;
            
            while(index<n && s[index]==' ')
                index++;
            while(index<n)
            {
                if(index-1>=0 && s[index]==' ' && s[index-1]==' ')
                {
                    index++;
                }
                else
                {
                    s[count] = s[index];
                    index++;
                    count++;
                }
            }
            
            s = s.substr(0, count);
            while(s.back()==' ')
                s.pop_back();
        }
    };

Log in to reply
 

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