最长公共子序列


最长公共子序列
参考  http://blog.csdn.net/zhongkeli/article/details/8847694  ---没有加 strA[lenA-1]==strB[lenB-1] ,有误
如最后一个7行6列是 4,6行5列是3 ,但是strA[7]是B ,strB[6]是A 所以不对,
要加strA[lenA-1]==strB[lenB-1] 判断
#include
   
   
    
    
#include
    
    
     
     
#include
     
     
      
      
#include
      
      
       
       

using namespace std;
string lcs(string strA, string strB) {
	int lenA = strA.size();
	int lenB = strB.size();
	
	// f[i][j] 存储的是strA中0 ~ i-1 与strB中0~j-1的公共子序列长度 ,i=0或j=0 表示strA或strB没有字符时的最长公共子序列,所以都是0
	vector
       
        
        
          > f(lenA+1,vector 
         
           (lenB+1,0)); for (int i = 0; i < lenA; i++) { for (int j = 0; j < lenB; j++) { if (strA[i] == strB[j]) f[i + 1][j + 1] = f[i][j] + 1; // i,j 的状态存储在 f[i+1][j+1] else f[i + 1][j + 1] = max(f[i][j + 1], f[i + 1][j]); } } int maxlen = f[lenA][lenB]; string commStr(maxlen,'a'); while (maxlen) { //一定 要有 strA[lenA - 1] == strB[lenB - 1] if (strA[lenA - 1] == strB[lenB - 1] && f[lenA][lenB] == f[lenA - 1][lenB - 1] + 1) { commStr[--maxlen] = strA[--lenA]; --lenB; } else if (f[lenA - 1][lenB] >= f[lenA][lenB - 1]) { --lenA; } else --lenB; } return commStr; } int main(int argc, char const *argv[]) { string A = "abcd"; string B = "bd"; cout << lcs(A, B); return 0; } 
          
         
       
      
      
     
     
    
    
   
   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值