题目来自网上
题目:求解两个字符串的最长公共子序列
举例:
strA = "ABCBDAB"
strB = "BDCABA"
字符串strA和strB的LCS为4.
思路:DP
代码
#include <iostream>
#include <assert.h>
#include <string>
using namespace std;
/*
f[i][j]:表示字符串strA[0~i]和字符串strB[0~j]最长公共子序列的长度
f[i][j] = f[i - 1][j - 1] + 1; strA[i] = strB[j]
= max{f[i][j - 1],f[i - 1][j]}; strA[i] != strB[j]
边界条件
f[0][j] = 0;
f[i][0] = 0;
*/
int LCS(char* pStrA,char* pStrB)
{
assert(pStrA != NULL && pStrB != NULL);
int f[20][20];
int nLenA = strlen(pStrA);
int nLenB = strlen(pStrB);
for (int i = 0;i < nLenA;i++)
{
f[i][0] = 0;
}
for (int j = 0;j < nLenB;j++)
{
f[0][j] = 0;
}
//递推
for (int i = 1;i < nLenA;i++)
{
for (int j = 1;j < nLenB;j++)
{
if (pStrA[i] == pStrB[j])
{
f[i][j] = f[i - 1][j - 1] + 1;
}
else
{
f[i][j] = max(f[i - 1][j],f[i][j - 1]);
}
}
}
return f[nLenA - 1][nLenB - 1];
}
int main()
{
char strA[50];
char strB[50];
string str;
//输入字符串A
cin>>str;
strA[0] = ' ';
for (int i = 0;i < str.size();i++)
{
strA[i + 1] = str[i];
}
strA[str.size() + 1] = 0;
//输入字符串A
cin>>str;
strB[0] = ' ';
for (int i = 0;i < str.size();i++)
{
strB[i + 1] = str[i];
}
strB[str.size() + 1] = 0;
cout<<LCS(strA,strB)<<endl;
system("pause");
return 1;
}