14. Longest Common Prefix (截取字符串)

Write a function to find the longest common prefix string amongst an array of strings.

char* longestCommonPrefix(char** strs, int strsSize) {
    if(strsSize==0) return "";
    
    char* ret = strs[0];
    int i, j;
    int cmpLen;
    for(int i = 1; i < strsSize; i++){ //traverse strs
        j = 0;
        cmpLen = (strlen(strs[i]) > strlen(ret))?strlen(ret):strlen(strs[i]);
        while(j < cmpLen && strs[i][j]==ret[j]) j++;
        ret[j] = '\0';
    }
    return ret;
}

 

posted on 2016-04-13 19:22  joannae  阅读(198)  评论(0编辑  收藏  举报

导航