#include<iostream>
#include<algorithm>
#include<cstdio>
#include<string.h>
#include<stack>
using namespace std;
const int MAXN = 1000 + 10;
int dp[MAXN][MAXN];
//dp[i][j]定义为L1串前i个与L2串前j个的LCS长度(不包括L1串第i个和L2串第j个)
char L1[MAXN];
char L2[MAXN];
char ans[MAXN][MAXN];
int main()
{
scanf("%s", L1);
getchar();
scanf("%s", L2);
int n=strlen(L1),m=strlen(L2);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if(L1[i-1]==L2[j-1]) dp[i][j]=dp[i-1][j-1]+1;
else dp[i][j]=max(dp[i][j-1],dp[i-1][j]);
}
}
//cout<<dp[n][m];
stack<char> s;
int i=n,j=m;
while(dp[i][j]){
if(dp[i][j]==dp[i-1][j]) i--;
else if(dp[i][j]==dp[i][j-1]) j--;
else{
s.push(L1[i-1]);
i--;
j--;
}
}
while(!s.empty()){
cout<<s.top();
s.pop();
}
return 0;
}
最长公共子序列LCS
最新推荐文章于 2022-06-05 08:58:34 发布