[算法导论读书笔记]最长公共子串

来源:互联网 发布:设备优化改善报告ppt 编辑:程序博客网 时间:2024/06/05 14:50

代码示例:

#include <stdio.h>#include <string.h>#define MAX 50char up = 'u', left = 'l', topLeftConer = 'c';void PrintLcs( char b[][MAX], char *x, int i, int j){if( i == 0 || j == 0)return;if( b[i][j] == topLeftConer ){PrintLcs( b, x, i-1, j-1);printf("%c", x[i -1]);}else if( b[i][j] == up ){PrintLcs( b, x, i - 1, j);}else{PrintLcs( b, x, i, j - 1);}}int LcsLength( char *x, char *y){int m = strlen(x);int n = strlen(y);int c[MAX][MAX];char b[MAX][MAX];int i, j;memset(c, 0, sizeof(c[0][0]) * (MAX * MAX) );memset(b, 0, sizeof(b[0][0]) * (MAX * MAX) );for( i = 1; i <= m; i++){for( j = 1; j <= n; j++){if( x[i-1] == y[j -1]){c[i][j] = c[i-1][j-1] + 1;b[i][j] = topLeftConer;}else if( c[i-1][j] >= c[i][j-1]){c[i][j] = c[i-1][j];b[i][j] = up;}else{c[i][j] = c[i][j-1];b[i][j] = left;}}}printf("the common substr is :");PrintLcs( b, x, m, n);return c[m][n];}int main(int argc, char* argv[]){char x[] = "asdbcesd";char y[] = "baseedd";puts(x);puts(y);printf("\nmax len: %d\n", LcsLength( x, y));return 0;}