动态规划-查找两个字符串的最长公共子串

 dp[i][j]表示str1的前i个字符与str2的前j个字符公共子串的长度。若str1[i-1]==str2[j-1],则dp[i][j]=dp[i-1][j-1]+1.

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string str1,str2;
    while(cin>>str1>>str2)
    {
        string ret;
        int s1=str1.size(),s2=str2.size();
        vector<vector<int>> dp(s1+1,vector<int>(s2+1,0));
        for(int i=1;i<s1+1;i++)
        {
            for(int j=1;j<s2+1;j++)
            {
                if(str1[i-1]==str2[j-1])
                {
                    dp[i][j]=dp[i-1][j-1]+1;
                    if(dp[i][j]>ret.size())
                    {
                        ret=str1.substr(i-dp[i][j],dp[i][j]);
                    }
                }
            }
        }
        cout<<ret<<endl;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/sinat_37903653/article/details/81089254