Simple C++ Solution


  • 0
    M
        string reverseWords(string s) {
            int start=0;
            for(int i=0;i<s.size();i++) {
                if(s[i]==' ') {
                    reverse(s, start, i-1);
                    start=i+1;
                }
            }
            reverse(s, start, s.size()-1);
            return s;
        }
        
        void reverse(string &s, int i, int j) {
            while(i<j) {
                char temp=s[i];
                s[i]=s[j];
                s[j]=temp;
                i++, j--;
            }
        }

Log in to reply
 

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