20170909_最长公共子序列的长度LCS

20170909_最长公共子序列的长度LCS


//给出两个字符串strA和strB,求出它们的最长公共子序列的长度。
//例如:strA="ABCBDAB",strB="BDCABA",则"BCBA"、"BDAB"均是他们的最长公共子序列,故其长度是4。

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

const int SIZE=100;
class LCSclass
{
public:
	int LCS_Length(const string &strA, const string &strB)
	{
		//描述最优解的结构,并且初始化
		if(strA.empty() == 1 || strB.empty() == 1)
			return 0;
		int m=strA.size();
		int n=strB.size();
		//cout<<m<<","<<n;
		for(int i=1; i<=m; ++i)
			c[i][0]=0;
		for(int i=1; i<=n; ++i)
			c[0][i]=0;
		c[0][0]=0;

		//按照自底向上的方式求解出最优解的值,填表
		for(int i=1; i<=m; ++i)
		{
			for(int j=1; j<=n; ++j)
			{
				if(strA[i-1]==strB[j-1])
					c[i][j]=c[i-1][j-1]+1;
				else
					c[i][j]=max(c[i-1][j],c[i][j-1]);
			}
		}
		int MaxLen=0;
		return MaxLen=c[m][n];
	}
private:
	int c[SIZE][SIZE];
};

int main(void)
{
	LCSclass object;
	string strA="ABCBDAB";
	string strB="BDCABA";
	//string strA="ABCDEFGA";
	//string strB="BCDEFGAABCDEFGA";
	//string strA="A";
	//string strB="B";
	int MaxLength=0;
	MaxLength=object.LCS_Length(strA,strB);
	cout<<"The Longest Common Subsequence of "<<strA<<" and "<<strB<<" is :"<<MaxLength<<endl;

	system("pause");
	return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值