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

本文介绍了一种寻找两个字符串间最长公共子串的有效方法。通过构建矩阵来追踪并记录最长公共子串的长度及位置,最终输出结果。此算法适用于需要识别文本中重复模式的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    有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);
}
测试正确。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值