问题描述
给定两个长度分别为N和M的字符串A和B,求既是A的子序列又是B的子序列的字符串长度最长是多少。
输入格式
第一行包含两个整数N和M。
第二行包含一个长度为N的字符串,表示字符串A。
第三行包含一个长度为M的字符串,表示字符串B。
字符串均由小写字母构成。
状态表示 dp[i][j]代表的是第一个序列的前i个字母,和第二个序列的前j个字母的公共子序列最大值
那么集合就可以分成四种 i,j都不选 只选i不选j, 只选j不选i,ij都选
代码
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
const int N = 1010;
string str1,str2;
int dp[N][N];
int LCS()
{
for(int i = 1; i <= str1.length(); i++)
{
for(int j = 1; j <= str2.length(); j++)
{
if(str1[i-1] == str2[j-1])
{
dp[i][j] = dp[i-1][j-1]+1;
}
else
{
dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
}
}
}
return dp[str1.length()][str2.length()];
}
int main(int argc, char** argv)
{
int n,m;
cin>>n>>m;
cin>>str1>>str2;
cout<<LCS()<<endl;
return 0;
}
该博客主要讨论了如何寻找两个字符串的最长公共子序列。通过动态规划的方法,使用二维数组dp来存储前i个字符和前j个字符的公共子序列的最大长度。当字符串的第i个字符和第j个字符相等时,公共子序列长度加1;否则,取两者中公共子序列长度的最大值。最后返回dp[str1.length()][str2.length()]作为最长公共子序列的长度。
1192

被折叠的 条评论
为什么被折叠?



