leetcode[14]:Longest Common Prefix

来源:互联网 发布:aocu2879vf接mac 编辑:程序博客网 时间:2024/05/16 17:20

Longest Common Prefix

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

char* longestCommonPrefix(char** strs, int strsSize) {    int i,j,flag=0;    char *res;    char tmp;    if(strsSize==0)    {        res=(char *)malloc(sizeof(char *)*1);        res[0]='\0';        return res;    }    if(strsSize==1)     {        if(strlen(strs[0])==0)         {            res=(char *)malloc(sizeof(char *)*1);            res[0]='\0';            return res;        }        res=(char *)malloc(sizeof(char *)*(strlen(strs[0])));        strcpy(res,strs[0]);        return res;    }    for(j=0;;j++)    {        tmp=strs[0][j];        if(!tmp) break;        for(i=1;i<strsSize;i++)        {            if(strs[i][j]!=tmp)             {                flag=1;                break;            }        }        if(flag) break;    }    res=(char *)malloc(sizeof(char *)*j);    memcpy(res,strs[0],j);    res[j]='\0';    return res;}

主要是各种空串之类的边界条件比较难弄,其他还好。

0 0