Tell me Why I am wrong?


  • 0
    C

    char* longestCommonPrefix(char** strs, int strsSize) {

    if(strlen(strs) == 0) return "";
    
    int i,j,len;
    len = strlen(strs[0]);
    
    for(i=0; i< strsSize; i++){
        if(len > strlen(strs[i])){// 获取第i行字符串的长度
            len = strlen(strs[i]);// 取较小的字符串长度
        }
        for(j=0; j<len; j++){
            if(strs[0][j] != strs[i][j]){
                len = j;
                break;
            }
        }
    }
    
    char* p = (char*) malloc(sizeof(char)*len+1);
    memcpy(p,strs[0],len);
    p[len]='\0';
    return p;
    

    }


  • 0

    You should check if strsSize is 0 and returns empty string. I didn't look at the rest part of the code and I am not familiar with C, so this may not be the reason.


  • 0
    C

    I should add this:
    if (strs == NULL || *strs == NULL)
    return "";


Log in to reply
 

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