[leetcode]最长公共前缀

 思路:

首先,我们将描述一种查找一组字符串的最长公共前缀 LCP(S_1 \ldots S_n)LCP(S1Sn) 的简单方法。 我们将会用到这样的结论:

LCP(S_1 \ldots S_n) = LCP(LCP(LCP(S_1, S_2),S_3),\ldots S_n)LCP(S1Sn)=LCP(LCP(LCP(S1,S2),S3),Sn)

算法

为了运用这种思想,算法要依次遍历字符串 [S_1 \ldots S_n][S1Sn],当遍历到第 ii 个字符串的时候,找到最长公共前缀 LCP(S_1 \ldots S_i)LCP(S1Si)。当 LCP(S_1 \ldots S_i)LCP(S1Si) 是一个空串的时候,算法就结束了。 否则,在执行了 nn 次遍历之后,算法就会返回最终答案 LCP(S_1 \ldots S_n)LCP(S1Sn)。

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

char* str=(char*)malloc(128);
memset(str,0,128);
int i,j=0;
if(strsSize<=1)
    return *(strs);
while(1)
{
    i=0;
    while(i<strsSize-1)
    {
        if(strs[i][j]!=strs[i+1][j])
            return str;
        i++;
    }
    str[j]=strs[0][j];
    j++;
}
return str;

猜你喜欢

转载自www.cnblogs.com/CuteyThyme/p/10652617.html
今日推荐