My accepted C solution


  • 0
    K

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

    if(strs == NULL || strs[0] == NULL)
    {
        return "";
    }
    
    if(strs[1] == NULL)
    {
        return strs[0];
    }
    
    char* str = (char*)malloc((strlen(strs[0])+1) * sizeof(char));
    strcpy(str, strs[0]);
    char* headOfStr = str;
    
    for(int i = 1; i < strsSize; i++)
    {
        char* temp = strs[i];
        while((*str) == (*temp) && (str != NULL) && (temp != NULL))
        {
            str++;
            temp++;
        }
        
        
        if(str != NULL)
        {
            *str = '\0';
        }
        
        str = headOfStr;
    }
    
    return str;
    

    }


Log in to reply
 

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