【动归经典】最长公共子串

来源:互联网 发布:中国网络教育大学 编辑:程序博客网 时间:2024/05/17 03:45

【问题描述】

    有两个字符串st和st2,现在可以从两个字符串中删去一些字符,使剩下的子串相同,问最长的相同子串长度是多少。

【分析】

    这道题是典型的动归,我们要从小的问题开始推,首先是st中一个字符在st2中的最长公共子串,然后到st中前两个字符在st2中的最长公共子串,以此类推,最后便可以得到答案。

【例程】

 

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;

int num[1000][1000];
string st,st2;
int len,len2;

int main()
{
 freopen("same.in","r",stdin);
 freopen("same.out","w",stdout);
 
 cin>>st>>st2;
 len=st.length();
 len2=st2.length();
 for(int i=1;i<=len;++i)
  for(int j=1;j<=len2;++j)
  {
   if(st[i-1]==st2[j-1])
    num[i][j]=num[i-1][j-1]+1;
   else
    num[i][j]=max(num[i-1][j],num[i][j-1]);
  }
 cout<<num[len][len2]<<endl;
 return 0;


0 0