最长公共子串LCS

找两个字符串的最长公共子串,这个子串要求在原字符串中是连续的。其实这又是一个序贯决策问题,可以用动态规划来求解。我们采用一个二维矩阵来记录中间的结果。这个二维矩阵怎么构造呢?直接举个例子吧:"bab"和"caba"(当然我们现在一眼就可以看出来最长公共子串是"ba"或"ab")

   b  a  b

c  0  0  0

a  0  1  0

b  1  0  1

a  0  1  0

我们看矩阵的斜对角线最长的那个就能找出最长公共子串。

不过在二维矩阵上找最长的由1组成的斜对角线也是件麻烦费时的事,下面改进:当要在矩阵是填1时让它等于其左上角元素加1。

   b  a  b

c  0  0  0

a  0  1  0

b  1  0  2

a  0  2  0

这样矩阵中的最大元素就是 最长公共子串的长度。

在构造这个二维矩阵的过程中由于得出矩阵的某一行后其上一行就没用了,所以实际上在程序中可以用一维数组来代替这个矩阵。

代码如下:

[cpp]  view plain copy
  1. #include<iostream>  
  2. #include<cstring>  
  3. #include<vector>  
  4. using namespace std;  
  5. //str1为横向,str2这纵向  
  6. const string LCS(const string& str1,const string& str2){  
  7.     int xlen=str1.size();       //横向长度  
  8.     vector<int> tmp(xlen);        //保存矩阵的上一行  
  9.     vector<int> arr(tmp);     //当前行  
  10.     int ylen=str2.size();       //纵向长度  
  11.     int maxele=0;               //矩阵元素中的最大值  
  12.     int pos=0;                  //矩阵元素最大值出现在第几列  
  13.     for(int i=0;i<ylen;i++){  
  14.         string s=str2.substr(i,1);  
  15.         arr.assign(xlen,0);     //数组清0  
  16.         for(int j=0;j<xlen;j++){  
  17.             if(str1.compare(j,1,s)==0){  
  18.                 if(j==0)  
  19.                     arr[j]=1;  
  20.                 else  
  21.                     arr[j]=tmp[j-1]+1;  
  22.                 if(arr[j]>maxele){  
  23.                     maxele=arr[j];  
  24.                     pos=j;  
  25.                 }  
  26.             }         
  27.         }  
  28. //      {  
  29. //          vector<int>::iterator iter=arr.begin();  
  30. //          while(iter!=arr.end())  
  31. //              cout<<*iter++;  
  32. //          cout<<endl;  
  33. //      }  
  34.         tmp.assign(arr.begin(),arr.end());  
  35.     }  
  36.     string res=str1.substr(pos-maxele+1,maxele);  
  37.     return res;  
  38. }  
  39. int main(){  
  40.     string str1("21232523311324");  
  41.     string str2("312123223445");  
  42.     string lcs=LCS(str1,str2);  
  43.     cout<<lcs<<endl;  
  44.     return 0;  
  45. }  

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值