Sharing my in place solution C++


  • 0
    X
    class Solution {
    public:
        void reverseWords(string &s) {
            if (s.length() == 0) return;
            int n = s.length();
            reverse(s, 0, n-1);
            
            int wHead = 0, wEnd = 0;
            while (wHead < n) {
                while (wEnd < n && s[wEnd] != ' ') wEnd++;
                if (wEnd == n) {
                    reverse(s, wHead, wEnd - 1); break;
                } else { // wEnd points to empty space
                    reverse(s, wHead, wEnd - 1);
                    wHead = wEnd + 1;
                    wEnd = wHead;
                }
            }
        }
      
        void reverse(string & s, int begin, int end) {
            while (begin < end) {
                char tmp = s[begin];
                s[begin] = s[end];
                s[end] = tmp;
                begin++;
                end--;
            }
        }
    };

Log in to reply
 

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