最长公共子序列Longest Common Subsequence

22 篇文章 0 订阅

求2个字符串的最长公共子序列(Longest Common Subsequence)

运用动态规划,复杂度为O(mn)m,n分别为两子序列长度

设:

两个序列Xi 和Yj的lcs为c[i,j]



如果图片显示不清楚,可在:

http://super-jiju.spaces.live.com/blog/cns!806C498DDEE76B61!270.entry

查看

 
根据上面的递归式即可

但不需要用递归求解,因为c[i,j]已经保存了每一对值
然后,回溯求得
#include  < iostream >
#include 
< string >
using   namespace  std;

int  lcs( string  A, string  B);
int  c[ 100 ][ 100 ] = {0} ;
int  b[ 100 ][ 100 ] = {0} ;
void  image( int  i, int  j, string   & A);
int  main()
{
    
string a,b;
    cin
>>a>>b;
    
if(a.length()>100 || b.length()>100)
    
{
        cerr
<<"Can not get the lcs of the string which length over 100"<<endl;
        exit(
0);
    }

    
string &aa=a;
    cout
<<" "<<endl;
    lcs(a,b);
    cout
<<" "<<endl;
    image(a.length(),b.length(),aa);    
    cout
<<endl;
    system(
"pause");
    
return 0;
}



int  lcs( string  A, string  B)
{
    
int    mA=A.length();
    
int nB=B.length();

    
int len=0;
    
for(int i=1;i<=mA;++i)
    
{
        
for(int j=1;j<=nB;++j)
        
{
            
if(A.at(i-1)==B.at(j-1))
            
{
                c[i][j]
=c[i-1][j-1]+1;
                len
++;
                b[i][j]
=3;
            }

            
else if(c[i-1][j]>=c[i][j-1])
            
{
                c[i][j]
=c[i-1][j];
                b[i][j]
=1;
                    
            }

            
else
            
{
                c[i][j]
=c[i][j-1];
                b[i][j]
=2;
            }

        }

    }



    
//-----image the road
    for(int j=1;j<=nB;++j)
    
{
        cout
<<" "<<B.at(j-1);
    }

    cout
<<endl;
    
for(int i=1;i<=mA;++i)
    
{
        cout
<<A.at(i-1)<<" "
        
for(int j=1;j<=nB;++j)
        
{
            cout
<<b[i][j]<<" ";
        }

        cout
<<" "<<endl;
    }


    
return len;

}

void  image( int  i, int  j, string   & A)
{

    
//-----3:up and left,1:up,2:left
    if(i==0||j==0)
        
return;
    
if (b[i][j]==3)
    
{
        cout
<<A.at(i-1)<<" ";
        image(i
-1,j-1,A);        
    }


    
if(b[i][j]==1)
        image(i
-1,j,A);
    
if(b[i][j]==2)
        image(i,j
-1,A);
}


比如输入结果:
ABCBDAB
BDCABA
得到:

        B       D       C       A       B       A
A       1       1       1       3       2       3

B       3       2       2       1       3       2

C       1       1       3       2       1       1

B       3       1       1       1       3       2

D       1       3       1       1       1       1

A       1       1       1       3       1       3

B       3       1       1       1       3       1



A       B       C       B(把顺序反过来即可)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值