Longest common substring(不连续子序列)

在前一篇文章中给出了最大连续子序列的实现

本文主要是算法导论中的不连续的最大子序列算法的一种实现。

输入:字符串str1和str2

输出:最大不连续子序列以及子序列的长度

 

#include  < iostream >
#include
< string >
using   namespace  std;

template
< class  T >
inline T max(T a, T b)
{
    
return a>b? a:b;
}


int  LookUp( string  str1, string  str2,  int  i,  int  j,  int **  c)
{
    
if(c[i][j]>-1)
        
return c[i][j];
    
if(!(i&&j))
        c[i][j]
=0;
    
else
        
if(str1[i]==str2[j])
            c[i][j]
=LookUp(str1,str2,i-1,j-1,c)+1;
        
else
            c[i][j]
=max(LookUp(str1,str2,i,j-1,c),LookUp(str1,str2,i-1,j,c));
    
    
return c[i][j];
}


void  print_LCS( string  str1,  string  str2, int **  c,  int  i,  int  j)
{
    
if(i==-1||j==-1)
        
return;
    
    
if(str1[i]==str2[j])
    
{
        print_LCS(str1, str2, c, i
-1, j-1);
        cout
<<str1[i]<<" "<<ends;
        
if(i==str1.size()-1)
            cout
<<endl;
    }

    
else
        
if(c[i-1][j]>c[i][j-1])
            print_LCS(str1, str2, c, i
-1, j);
        
else
            print_LCS(str1, str2, c, i, j
-1);
}


    
int  LCS_length( string  str1,  string  str2)
{
    
int m=str1.size()+1;
    
int n=str2.size()+1;

    
int** c=new int* [m];
    
int i,j;
    
for(i=0;i<m;++i)
        c[i]
=new int[n];

    
for(i=0;i<m;++i)
        
for(j=0;j<n;++j)
            c[i][j]
=-1;



    
int len=LookUp(str1,str2,m-1,n-1,c);
    
/*    for(i=0;i<m;++i)
    {
        for(j=0;j<n;++j)
            cout<<c[i][j]<<"  "<<ends;
        cout<<endl;
    }
*/
    
    print_LCS(str1,str2,c,m
-1,n-1);

    
for(i=0;i<m;++i)
        delete[] c[i];
    delete[] c;

    
return len;
}


int  main()
{
    
string str1("10010101");
    
string str2("010110110");
    cout
<<"str1:"<<str1<<endl;
    cout
<<"str2:"<<str2<<endl;
    cout
<<LCS_length(str1,str2)<<endl;

    
return 0;
}


 输出结果:

str1:10010101
str2:010110110
010101

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值