公共子串(动态规划)

Description

设有A、B两个字符串,找出A、B共同子串,每个字符串无相同字符,可以不连续,但顺序不能颠倒。

Input

第一行字符串A 
第二行字符串B 

Output

最长公共子串的长度.

Sample Input

 

abcfbc
abfcab

 

Sample Output

 

4
 
 
解题思路:
c[i,j]表示序列x[i]和y[i]的最长公共子序列的长度,状态转移方程为:
c[i,j]={{0|i=1,j=1},{c[i-1,j-1]+1|x=y},{max{c[i,j-1],c[i-1,j]}|x<>y}}
(1<=i<=lenx,1<=j<=leny)
c[lenx,leny]即为所求。
时间复杂度:O(n^2)
 
 
程序:

const
  maxlen=200;
var
  i,j:longint;
  c:array[0..maxlen,0..maxlen]of longint;
  x,y,z:string;
begin
  readln(x);
  readln(y);
  for i:=1 to length(x) do
    for j:=1 to length(y) do
      if x[i]=y[j] then c[i,j]:=c[i-1,j-1]+1
        else if c[i-1,j]>c[i,j-1] then c[i,j]:=c[i-1,j]
          else c[i,j]:=c[i,j-1];
  i:=length(x);
  j:=length(y);
  writeln(c[i,j]);
while (i>0) and (j>0) do
    if x[i]=y[j] then begin z:=z+x[i]; dec(i); dec(j); end
      else if c[i-1,j]>c[i,j-1] then dec(i)
        else dec(j);
  if z<>'' then writeln(z);}
end.

 

 

版权属于: Chris

原文地址: http://blog.sina.com.cn/s/blog_83ac6af80102vjrt.html

转载时必须以链接形式注明原始出处及本声明。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值