1. 最长公共子串
注意子串是连续的。有下列动态转移方程
c[i][j] = c[i-1][j-1] + 1 when X[i] = Y[j]
c[i][j] = 0 when X[i] != Y[j]
1 c[100][100]; 2 3 int LCS(char x[], int len_x, char y[], int len_y){ 4 5 int max_len = 0; 6 7 for(int i =0; i < len_x ; i++){ 8 for(int j = 0; j < len_y; j++){ 9 if(x[i] == y[j]){ 10 if(x && y) 11 c[i][j] = c[i-1][j-1] + 1; 12 if(x == 0 || y == 0) 13 c[i][j] = 1; 14 if(c[i][j] > max_len) 15 max_len = c[i][j]; 16 } 17 } 18 } 19 20 return max_len; 21 }
2. 最长公共子序列
子序列不要求连续。
有下列状态转移方程
c[i][j] = c[i-1][j-1] + 1 if x[i] == y[j]
c[i][j] = max{c[i-1][j], c[i][j-1]} if x[i] != y[j]
// x = "+AB" y = "+CD" int c[100][100] = 0; int lcs(char x[], char y[]){ int m = strlen(x); int n = strlen(y); for(int i = 1; i<=m; i++) for(int j = 1; j <= n; j++){ if(x[i] == y[j]) c[i][j] = c[i-1][j-1] + 1; else c[i][j] = max(c[i][j-1], c[i-1][j]); } return c[m][n]; }
时间: 2024-10-03 14:41:49