LCS最长公共子序列
#include<stdio.h>
#include<string.h>
#include<stack>
#include<algorithm>
using namespace std;
#define N 1010
int dp[N][N];
char c;
int main()
{
char a[N];
char b[N];
scanf("%s%s",a,b);
int la=strlen(a);
int lb=strlen(b);
memset(dp,0,sizeof(dp));
for(int i=1; i<=la; i++)
{
for(int j=1; j<=lb; j++)
{
if(a[i-1]==b[j-1])
dp[i][j]=dp[i-1][j-1]+1;
else
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
int i=la,j=lb;
stack<char>s;
while(dp[i][j])
{
if(dp[i][j]==dp[i-1][j])///来自于左方向
{
i--;
}
else if(dp[i][j]==dp[i][j-1])///来自于上方向
{
j--;
}
else if(dp[i][j]>dp[i-1][j-1])///来自于左上方向
{
i--;
j--;
s.push(a[i]);
}
}
while(!s.empty())
{
c=s.top();
printf("%c",c);
s.pop();
}
return 0;
}
例题:
https://leetcode-cn.com/problems/longest-common-subsequence/submissions/
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int dp[1001][1001];
int lena = text1.size(),lenb = text2.size();
int maxx = -0x3f3f3f3f;
for(int i=1;i<=lena;i++){
for(int j=1;j<=lenb;j++){
if(text1[i-1]==text2[j-1]){
dp[i][j] = dp[i-1][j-1]+1;
}else{
dp[i][j] = max(dp[i][j-1],dp[i-1][j]);
}
}
}
return dp[lena][lenb];
}
};