方法一:动态规划 效率O(mn)(mn是分别是两个字符串的长度)
#include<iostream> using namespace std; int c[100][100];//全局变量自动初始化为0 inline int max(int a, int b) { return (a > b ? a : b); } int LCS(const char *X,const char *Y) { if (NULL == X || NULL == Y) return 0; int xlen = strlen(X); int ylen = strlen(Y); for (int i = 1; i <= xlen; i++) { for (int j = 1; j <= ylen; 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[xlen][ylen]; } int main() { char A[8] = "ABCBDAB"; char B[8] = "BDCABAB"; cout << LCS(A, B) << endl; system("pause"); return 0; }
方法二:低效的递归算法
#define INF 9999999 int c[100][100]; int LCS_Memo(const char* X, const char* Y,int i,int j) { if (c[i][j] < INF) return c[i][j]; if (0 == i || 0 == j) c[i][j] = 0; else if (X[i - 1] == Y[j - 1]) c[i][j] = LCS_Memo(X,Y,i - 1, j - 1) + 1; else { int p = LCS_Memo(X, Y, i - 1, j); int q = LCS_Memo(X, Y, i, j - 1); if (p >q) c[i][j] = p; else { c[i][j] = q; } } return c[i][j]; } int LCS(const char* X ,const char* Y) { if (NULL == X || NULL == Y) return 0; int xlen = strlen(X); int ylen = strlen(Y); memset(c, INF, sizeof(c));//注意是将每个字节赋值为INF,不是一个int return LCS_Memo(X, Y, xlen, ylen); } int main() { char A[8] = "ABCBDAB"; char B[8] = "BDCABAB"; cout << LCS(A, B) << endl; system("pause"); return 0; }
时间: 2024-10-15 09:39:21