C in-place O(1) space solution


  • 0
    A

    No library function dependency.

    22 / 22 test cases passed
    Status: Accepted
    Runtime: 0 ms

    void reverseWords(char *s) {
        char *p, *q, *b = s, *e = s;
        while (*e && *e == ' ') e++;
        while (*b) {
            for (p = b; *e && *e != ' '; b++, e++) {
                if (e != b) *b = *e;
            }
            for (q = b-1; q > p; q--, p++) {
                char t = *q;
                *q = *p, *p = t;            
            }
            while (*e && *e == ' ') e++;
            if (*e) { *b++ = ' '; }
            else { *b-- = NULL; break; }
        }
        for (e = s; b > e; b--, e++) {
            char t = *e;
            *e = *b, *b = t;
        }
    }
    

Log in to reply
 

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