C++ two passes solution


  • 0
    M

    The first pass is to reverse the entire string in-place using swaps. The second pass is to go through the string and reverse each word in-place using swaps. Please share if you can do this problem in-place using just a single pass.

    void reverseWords(string &s) {
            const int n = s.length();
            int l = 0, r = n-1;
            while(l < r) swap(s[l++],s[r--]); // first pass
            
            l = 0;
            for(int i=0; i<n; i++) { // second pass
                if(s[i] == ' ') {
                    r = i-1;
                    while(l < r) swap(s[l++],s[r--]);
                    l = i+1;
                }
            }
            r = n-1;
            while(l < r) swap(s[l++],s[r--]);
        }

  • 0
    R
    This post is deleted!

Log in to reply
 

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