欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

求两个字符串共同子串的长度

程序员文章站 2024-02-26 15:35:22
...

给定两个字符串,找出最长的共同子串,返回它的长度。

例如:A="ABCD", B="CBCE",返回2.

注意:在substring中的字符应当在原string中连续。而subsequence不是连续的。

int longCommonSubstring(string& A,string&B)
{
    if(A.empty() || B.empty())
    {
        return 0;
    }

    int lcs = 0;
    int lcs_tmp;
    
    for(int i=0;i<A.size();i++)
    {
        for(int j=0;j<B.size();j++)
        {
            lcs_tmp = 0;
            while((i+lcs_tmp < A.size())&& \
                  (j+lcs_tmp < B.size())&& \
                  (A[i+lcs_tmp] == B[j+lcs_tmp]))
            {
                ++lcs_tmp;
            }
            
            if(lcs_tmp > lcs)
            {
                lcs = lcs_tmp;
            }
        }
    }

    return lcs;
}