最长公共子串(Longest common substring)

问题描述:

    给定两个序列 X=<x1, x2, ..., xm>, Y<y1, y2, ..., yn>,求X和Y长度最长的公共子串。(子串中的字符要求连续)

    这道题和最长公共子序列(Longest common subsequence)很像,也可以用动态规划定义。公式如下:

这里c[i,j]表示以Xi,Yj结尾的最长公共子串的长度。

程序实现:

int longestCommonSubstring(string x, string y)
{
    int m = x.length();
    int n = y.length();
    vector< vector<int> > c(m+1, vector<int>(n+1));
    for (int i = 0; i <= m; ++i)
        c[i][0] = 0;
    for (int j = 1; j <= n; ++j)
        c[0][j] = 0;

    int len = 0;
    for (int i = 1; i <= m; ++i)
    {
        for (int j = 1; j <= n; ++j)
        {
            if (x[i-1] == y[j-1])
            {
                c[i][j] = c[i-1][j-1] + 1;
                if (c[i][j] > len)
                    len = c[i][j];
            else
                c[i][j] = 0;
        }
    }
    return len;
}

reference:

算法设计 - LCS 最长公共子序列&&最长公共子串 &&LIS 最长递增子序列

华为OJ2011-最长公共子串

转载于:https://www.cnblogs.com/gattaca/p/4725400.html

猜你喜欢

转载自blog.csdn.net/weixin_33881041/article/details/93401846