A different one pass solution, it differs from the official two solutions


  • 0
    S
    // one pass: O(n) time
    void reverseWords(string &s) {
        string str, tmp;
        const char *p = s.c_str();
        
        while (*p) {
            while (*p && *p == ' ') ++p; // pass the multiple spaces
            tmp.clear();
            while(*p && *p != ' ') tmp.append(1, *p++);
            if (!tmp.empty()) str = str.empty() ? tmp : (tmp + " " + str);
        }
        
        s = str;
    }

Log in to reply
 

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