最长子串问题

//关于最长公共子串的一些简单想法
//  if 求 str1 与 str2 的最长公共子串,可以将str1 每个字符与str2 每个字符建立矩阵 Grape[len1][len2]
//  遍历 如果 str1[i]==str2[j] 则Grape[i][j] = 1
//  因此最长的公共子串为Grape图中最长的1对角线长
//  因此优化下
//  if
//      str1[i] != str2[j] Grape[i][j] = 0;
//  else
//      Grape[i][j] = Grape[i-1][j-1] + 1
// 最长公共子串即为图中最大的值
//  C实现
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
const int maxn = 1e4 + 15;
int dp[maxn][maxn];
int lset(const string& s1,const string& s2)
{
    memset(dp,0,sizeof(dp));
    int maxLen = 0;
    for(int i=1;i<=s1.length();++i)
    {
        for(int j=1;j<=s2.length();++j)
        {
            if(s1[i-1]==s2[j-1])
            {
                dp[i][j] = dp[i-1][j-1] + 1;
                maxLen = max(maxLen,dp[i][j]);
            }
        }
    }
    return maxLen;
}
int main()
{
    string str1,str2;
    while(cin>>str1>>str2)
    {
        cout<<lset(str1,str2)<<endl;
    }
}

 

posted on 2019-09-21 00:13  chengyulala  阅读(259)  评论(0编辑  收藏  举报

导航