最长公共子序列求解

来源:互联网 发布:胖熊数据库分享 编辑:程序博客网 时间:2024/06/05 06:47

求多个字符串的最长公共子序列可以转化为逐步求2个字符串的最长公共子序列来求解直至收敛,虽然过程会比较复杂一些。

下面的代码将采用动态规划的方法来求解2个字符串的最长公共子序列的问题,当然里面还包含了测试例子

关于本代码的详情解释请看算法导论第二版 机械工业出版社 15章动态规划15.3,看了你再运行代码你会更容易明白

#include <iostream>#include <string>using namespace std;#define MAX 1000int c[MAX][MAX];int b[MAX][MAX];bool LCS_LENGTH(string x, string y){int m = x.length();int n = y.length();int i;int j;for(i = 1; i <= m; i++){c[i][0] = 0;}for(j = 0; j <= n; j++){c[0][j] = 0;}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] = 2; // 2 is stand for left and up}else if(c[i - 1][j] >= c[i][j - 1]){c[i][j] = c[i - 1][j];b[i][j] = 1; // 1 si stand for up}else{c[i][j] = c[i][j - 1];b[i][j] = 3; // 3 is stand for left}}}return true;}bool PRINT_LCS(string x, int i, int j){if(i == 0 || j == 0){cout<<endl;return true;}if(b[i][j] == 2){PRINT_LCS(x, i - 1, j - 1);cout<<x[i - 1];}else if(b[i][j] == 1){PRINT_LCS(x, i - 1, j);}else{PRINT_LCS(x, i, j - 1);}}int main(){string x = "abcbdab";string y = "bdcaba";LCS_LENGTH(x, y);cout<<c[x.length()][y.length()]<<endl;PRINT_LCS(x, x.length(), y.length());while(1);return 0;}