思路:dp[i][j]的含义为str1[0..i]与str2[0..j]的最长公共子序列长度.
#include<iostream>
#include<string>
using namespace std;
const int maxn = 100;
int main()
{
string str1,str2;
cin>>str1;
cin>>str2;
int dp[maxn][maxn];
for(int i = 0; i < str1.length(); i++)
{
if(dp[i - 1][0] == 1)
{
dp[i][0] = 1;
continue;
}
if(str1[i] == str2[0])
{
dp[i][0] = 1;
}
else
dp[i][0] = 0;
}
for(int j = 0; j < str2.length(); j++)
{
if(dp[0][j -1] == 1)
{
dp[0][j] = 1;
continue;
}
if(str1[0] == str2[j])
{
dp[0][j] = 1;
}
else
dp[0][j] = 0;
}
for(int i = 1; i < str1.length(); i++)
{
for(int j = 1; j < str2.length(); j++)
{
if(str1[i] == str2[j])
dp[i][j] = max(max(dp[i -1][j],dp[i][j - 1]),dp[i-1][j-1]+1);
else
dp[i][j] = max(dp[i - 1][j],dp[i][j - 1]);
}
}
cout<<dp[str1.length() - 1][str2.length() - 1]<<endl;
return 0;
}
来源:51CTO
作者:wx5d3c7e0ad6c30
链接:https://blog.51cto.com/14472348/2474136