求2个字符串的最长公共子串——矩阵法

来源:互联网 发布:奔腾楚天激光机编程 编辑:程序博客网 时间:2024/06/01 10:05

    有2个字符串,求它们的最长的公共子串,不是公共子序列,要连续。

    例如:str1=“abcabce",str2="bcacabcgef",那么最长的公共子串为”cabc“。

    最直观的办法是用矩阵法,累计记录最长子串的长度和位置。

int hjd_longest_common_substr(char *str1, char *str2, char *strresult){    int lcs_len=0, mx=0, my=0;    int nlen1 = strlen(str1), nlen2 = strlen(str2);    *strresult = '\0';    int AR[nlen2][nlen1];    int x=0, y=0;    for(y=0; y<nlen2; y++)        for(x=0; x<nlen1; x++)        {            AR[y][x]=0;        }    for(y=0;y<nlen2;y++)    {        for(x=0;x<nlen1;x++)        {            if(*(str1+x)==*(str2+y))            {                if((x==0)||(y==0))                {                    AR[y][x] = 1;                }                else                {                    AR[y][x] = AR[y-1][x-1] + 1;                }                if (AR[y][x]>lcs_len)                {                    //记录最长子串的长度和结束的位置                    lcs_len=AR[y][x];                    mx=x;                    my=y;                }            }        }    }    if(lcs_len>0)    {        int i=0;        for(i=0;i<lcs_len;i++)        {            *(strresult+i) = *(str1 + mx - AR[my][mx] + 1 + i);            printf("%c\t", *(str1 + mx - AR[my][mx] + 1 + i));        }        *(strresult + i) = '\0';    }    return(lcs_len);}
测试正确。

0 0
原创粉丝点击