程式語言 - LeetCode - C - 14. Longest Common Prefix



題目:


解答:

char* longestCommonPrefix(char **strs, int strsSize)
{
    int i = 0;
    int j = 0;
    int len = 200;
    int tmp = 0;
    int idx = 0;
    int found = 0;
    
    for (i = 0; i < strsSize; i++) {
        tmp = strlen(strs[i]);
        if (len > tmp) {
            len = tmp;
        }
    }
    
    char *p = calloc(len + 1, 1);
    for (i = 0; i < len; i++) {
        found = 0;
        for (j = 1; j < strsSize; j++) {
            if (strs[j][i] != strs[0][i]) {
                found = 1;
                break;
            }
        }
        
        if (found) {
            break;
        }
        p[idx++] = strs[0][i];
    }
    return p;
}