#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 100
//最长公共子序列
int LCS(const char *a, const char *b, char *result);
int main(void)
{
char *a = "ABCBDAB";
char *b = "BDCABA";
char result[MAXSIZE];
printf("%d\n", LCS(a, b, result));
printf("%s\n", result);
return 0;
}
int LCS(const char *a, const char *b, char *result)
{
int i;
int j;
int count;
int d[MAXSIZE][MAXSIZE];
int lengthA = strlen(a);
int lengthB = strlen(b);
//初始化第0列
for (i = 0; i <= lengthA; ++i)
{
d[i][0] = 0;
}
//初始化第0行
for (i = 0; i <= lengthB; ++i)
{
d[0][i] = 0;
}
for (i = 1; i <= lengthA; ++i)
{
for (j = 1; j <= lengthB; ++j)
{
//如果相等
if (a[i - 1] == b[j - 1])
{
d[i][j] = d[i - 1][j - 1] + 1;
}
//d[i][j - 1]较大
else if (d[i - 1][j] <= d[i][j - 1])
{
d[i][j] = d[i][j - 1];
}
//d[i - 1][j]较大
else
{
d[i][j] = d[i - 1][j];
}
}
}
//长度
count = d[lengthA][lengthB];
result[count] = '\0';
i = lengthA;
j = lengthB;
while (i != 0 && j != 0)
{
if (a[i - 1] == b[j - 1])
{
result[--count] = a[i - 1];
--i;
--j;
}
else if (d[i][j - 1] <= d[i - 1][j])
{
--i;
}
else
{
--j;
}
}
return d[lengthA][lengthB];
}