My pure C solution, assume free will be called by caller


  • 0
    Y
    int min(int a, int b){
        return a<b?a:b;
    }
    
    char* longestCommonPrefix(char** strs, int strsSize) {
        if(strs == NULL) return strs;
        if(strsSize == 0) return "";
        int bound = strlen(strs[0]);
        for(int i=1;i<strsSize;i++){
            int len = strlen(strs[i]);
            bound = min(bound, len);
            for(int j=0;j<bound;j++){
                if(strs[0][j] != strs[i][j]){
                    bound = j; break;
                }
            }
        }
        char* result = (char*) malloc(bound*sizeof(char)+1);
        memcpy(result, strs[0], bound);
        result[bound] = '\0';
        
        return result;
    }

Log in to reply
 

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