#include <iostream>
#include <assert.h>
#include <string>
using namespace std;
#define Max(a,b) (a)>(b)?(a):(b)
int main(void)
{
string str1 = "abcdss";
string str2 = "asbda";
int len1 = str1.length();
int len2 = str2.length();
int A[50][50] = { 0 };
for (int i = 1; i <= len1; i++)
{
for (int j = 1; j <= len2; j++)
{
if (str1[i-1] == str2[j-1])
{
A[i][j] = A[i - 1][j - 1] + 1;
}
else
{
A[i][j] = Max(A[i - 1][j], A[i][j - 1]);
}
}
}
cout << "最长公共子序列元素个数: "<<A[len1][len2]<<endl;
cout << "最长公共序列(逆序)" << endl;
for (int i = len1-1,j = len2-1; i >= 0 && j >= 0; )
{
if (str1[i] == str2[j])
{
cout << str1[i];
i--; j--;
}
else
{
if (A[i][j+1] >= A[i+1][j])
{
i--;
}
else
{
j--;
}
}
}
return 0;
}
参考博客:
http://www.cnblogs.com/huangxincheng/archive/2012/11/11/2764625.html
最长公共子序列
最新推荐文章于 2023-06-01 19:25:01 发布