[C] 6ms code using stack with O(n)


  • 0

    Didn't see anyone here use stack to solve this. I think using stack here is quite intuitive.

    My ugly code :P Any improvements are welcome!

    char* reverseWords(char* s) {
        char stack[500];
        char* p = s;
        int newTop = -1, top = -1;
        // start the pointer.
        while(*p != '\0') {
            // push into stack.
            stack[++top] = *p;
            // pop out of stack.
            if(*p == ' ') {
                // here's a space, go back one position.
                --top;
                while(top != -1) 
                    s[++newTop] = stack[top--];
                s[++newTop] = ' ';
            }
            ++p;
        }
        // clear out the rest in the stack.
        while(top != -1)
            s[++newTop] = stack[top--];
        s[++newTop] = '\0';
    
        return s;
    }
    

    Also works well with strings separated by multiple spaces.


Log in to reply
 

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