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;
}