Hello everyone, this is my solution, while leetcode told me WA. It's wired that output and expected are the same?


  • 0
    P
    void reverseWords(char *s)
    {
        if (!s && *s == 0)
            return;
        char *start;
        for (start = s; *start == ' '; ++start);
        if (*start == 0)
        {
            *s = 0;
            return;
        }
        char *end;
        for (end = s + strlen(s) - 1; *end == ' '; --end);
        
        char ch;
        char *i, *j;
        for (i = start, j = end; i < j; ++i, --j)
        {
            ch = *i;
            *i = *j;
            *j = ch;
        }
        
        char *next_i;
        for (i = start; i <= end;)
        {
            for (j = i + 1; j <= end && *j != ' '; ++j);
            next_i = j + 1;
            for (j = j - 1; i < j; ++i, --j)
            {
                ch = *i;
                *i = *j;
                *j = ch;           
            }
            i = next_i;
        }
        
        for (i = start, j = s; i <= end; ++i, ++j)
            *j = *i;
        *j = 0;
    }

  • 0
    P

    here is the result of leetcode:
    Input: " a b "
    Output: "b a"
    Expected: "b a"


  • 1
    L

    Input: " a b " may means there are multiple spaces between a and b even it looks like only one
    and so is the output
    so you have to deal with the case mentioned in the Clarification :
    How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.


  • 0
    P

    thx, i didn't read the clarification carefully. Problem was solved!


Log in to reply
 

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