A strange output.Why is it?


  • 0
    B
    char* longestCommonPrefix(char** strs, int strsSize) {
    if(strs[0]==NULL)
    {
        return "";
    }
    int n=strlen(strs[0]);
    int i=0;
    char * s;
    s=(char *)malloc((n+1)*sizeof(char));
    while(strs[0][i]!='\0')
    {
        for(int j=1;j<strsSize;j++)
        {
            if(strs[j][i]!=strs[0][i])
            {
                return s;
            }
        }
        s[i]=strs[0][i];
        i++;
        s[i]='\0';
    }
    return s;
    

    }

    Input:
    ["ca","a"]

    Output:
    "��|"

    Expected:
    ""

    But when I run code in Custom Testcase ,the result is right.


  • 0
    W

    when using malloc function, you should clear the buffer at first

    void *memset(void *s, int ch, size_t n);


Log in to reply
 

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