//最长公共子序列
//ab34c
//a1bc2
#include <iostream>
#include <string>
using namespace std;
int max(int a, int b)
{
if (a > b)
{
return a;
}
return b;
}
string dp(string str1, string str2)
{
int len1 = str1.length();
int len2 = str2.length();
int** dp = new int* [len1];
int maxnum = 0;
string ans = "", temp;
for (int i = 0; i < len2; i++)
{
dp[i] = new int[len2];
}
//第一行
for (int i = 0; i < len1; i++)
{
if (str2[0] == str1[i])
{
dp[0][i] = 1;
}
else
{
if (i - 1 >= 0 && dp[0][i - 1] == 1)
{
dp[0][i] = 1;
}
else
{
dp[0][i] = 0;
}
}
}
//第一列
for (int j = 0; j < len2; j++)
{
if (str1[0] == str2[j])
{
dp[j][0] = 1;
}
else
{
if (j - 1 >= 0 && dp[j - 1][0] == 1)
{
dp[j][0] = 1;
}
else
{
dp[j][0] = 0;
}
}
}
for (int j = 1; j < len2; j++)
{
for (int i = 1; i < len1; i++)
{
maxnum = max(dp[j - 1][i], dp[j][i - 1]);
if (str1[i] == str2[j])
{
dp[j][i] = max(dp[j - 1][i - 1], maxnum) + 1;
}
else
{
dp[j][i] = maxnum;
}
}
}
for (int j = 0; j < len2; j++)
{
for (int i = 0; i < len1; i++)
{
cout << dp[j][i];
}
cout << endl;
}
len1--;
len2--;
while (len1 > 0 && len2 > 0)
{
if (dp[len2][len1] > max(dp[len2 - 1][len1], dp[len2][len1 - 1]))
{
temp = str1[len1];
ans.insert(0, temp);
len1--;
len2--;
}
else
{
if (dp[len2 - 1][len1] > dp[len2][len1 - 1])
{
len2--;
}
else
{
len1--;
}
}
if ((len1 == 0 && dp[len2][len1]!=0))
{
temp = str1[len1];
ans.insert(0, temp);
}
else if ((len2 == 0 && dp[len2][len1] != 0))
{
temp = str1[len2];
ans.insert(0, temp);
}
}
for (int i = 0; i < len2; i++)
{
delete[] dp[i];
}
delete[]dp;
return ans;
}
int main()
{
string str1, str2;
cin >> str1 >> str2;
cout << dp(str1, str2);
return 0;
}
DP最长公共子序列
最新推荐文章于 2022-07-08 14:21:40 发布