C++ solution very easy to understand


  • 0
    Q
    class Solution {
    public:
        string reverseWords(string s) {
            int i = 0, len = s.size();
            while(i<len){
                int cur = i;
                while(i<len && s[i]!=' ')
                    i++;
                if(i == cur)
                    i++;
                else
                    reverse(s,cur,i-1);
            }
            return s;
        }
        
        void reverse(string &s, int i, int j){
            while(i<j){
                char ch = s[i];
                s[i++] = s[j];
                s[j--] = ch;
            }
            return;
        }
    };
    

Log in to reply
 

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