C solution, runtime O(n), memory O(n)


  • 0
    Y

    solution:

    void reverseWords(char *s) {
        int len = strlen(s);
        char* tmp = (char*)malloc(len);
        char* dest = tmp + len;
        int i = 0;
        int wordLen = 0;
        for (i = 0; i < len; i++) {
            if (s[i] != ' ') {
                 wordLen++;
            }
            else if (wordLen > 0) {
                dest -= (wordLen+1);
                memcpy(dest + 1, s + i - wordLen, wordLen);
                wordLen = 0;
                *dest = s[i];
            }
        }
    
        dest -= wordLen;
        memcpy(dest, s + i - wordLen, wordLen);
        while (*dest == ' ') dest++;
        memset(s, 0, len);
        memcpy(s, dest, len - (dest - tmp));
        free(tmp);
    }
    

Log in to reply
 

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