假设X={x1.x2,...xm}, Y={y1,y2,...yn}为两个序列,并设Z={z1,z2,z3...zk}为X,Y的一个最常公共子序列。则有:
(1)xm=yn的时候zk=xm=yn而且Zk-1是Xm-1和Yn-1的一个LCS
(2)xm!=yn的时候,zk!=xm,蕴含Z是Xm-1和Y的一个LCS
(3)xm!=yn的时候,zk!=yn,蕴含Z是X和Yn-1的一个LCS
下面贴上C代码,伪代码大家可以参考算法导论:
#include<stdio.h>
#include<stdlib.h>
#include<memory.h>
int **get_longest_common_subsequence(char *x, int len_x, char *y, int len_y,int **b)
{
int i, j;
int **c= (int**)malloc(sizeof(int*) * (len_x + 1));
for(i = 0; i <= len_x; i++)
c[i] = (int*) malloc(sizeof(int) * ( len_y + 1));
for(i = 0; i <= len_x; i++)
c[i][0] = 0;
for(j =0; j <= len_y; j++)
c[0][j] = 0;
for(i = 1; i <= len_x; i++) {
for(j = 1; j <= len_y; j++) {
if(x[i] == y[j]) {
c[i][j] = c[i-1][j-1]+1;
b[i][j] = 1;
} else if(c[i-1][j] >= c[i][j-1]) {
c[i][j] = c[i-1][j];
b[i][j] = 2;
} else {
c[i][j] = c[i][j-1];
b[i][j] = 3;
}
}
}
return c;
}
void print(char *x, int i, int j, int **b) {
if(i == 0 || j == 0)
return;
if(b[i][j] == 1) {
print(x, i-1, j-1, b);
printf("%c\t", x[i]);
} else if(b[i][j] == 2) {
print(x, i-1, j, b);
} else {
print(x, i, j-1, b);
}
}
void main()
{
char x[] = {' ','A', 'B', 'C', 'B', 'D', 'A', 'B'};
char y[] = {' ','B', 'D', 'C', 'A', 'B', 'A'};
int len_x = sizeof(x)/sizeof(char) - 1;
int len_y = sizeof(y)/sizeof(char) - 1;
printf("%d\t%d\n",len_x,len_y);
int **b= (int**)malloc(sizeof(int*) * (len_x + 1));
for(int i = 0; i <= len_x; i++)
b[i] = (int*) malloc(sizeof(int) * ( len_y + 1));
get_longest_common_subsequence(x, len_x, y, len_y, b);
print(x, len_x, len_y, b);
printf("\n");
free(b);
}