#include<iostream>
#include<algorithm>
using namespace std;
string word1;
string word2;
int n1,n2;
int s[2000][2000];
void dp()
{
for (int i = 1; i <= n1; i++)
{
for (int j = 1; j <= n2; j++)
{
if (word1[i-1] == word2[j-1])
{
s[i][j] = s[i - 1][j - 1]+1;
//s[i][j]代表当word1长度为i,word2长度是j时,最长公共子串长度
//DP在从长度从小往大存
}
else
{
s[i][j] = max(s[i - 1][j], s[i][j - 1]);
}
}
}
}
int main()
{
cin>>word1>>word2;
n1=word1.length();
n2=word2.length();
dp();
cout << s[n1][n2];//
}
中国矿业大学——算法实验1,2——最长公共子序列
最新推荐文章于 2025-12-03 17:03:32 发布
该代码使用动态规划方法求解两个字符串word1和word2的最长公共子串的长度。通过比较word1和word2的每个字符,更新二维数组s[i][j],存储以word1的第i个字符和word2的第j个字符结尾的最长公共子串的长度。
164





