Java实现最长公共子序列

来源:互联网 发布:淘宝网忘了密码怎么办 编辑:程序博客网 时间:2024/05/22 03:47

最长公共子序列(LCS)定义:

一个数列 S,如果分别是两个或多个已知数列的子序列,且是所有符合此条件序列中最长的,则 S 称为已知序列的最长公共子序列。比如数列A = “abcdef”, B = “adefcb”. 那么两个数列的公共子序列是"adef". 

最长公共子序列和最长公共子字符串是有区别的,公共子序列里的元素可以不相邻,但是公共子字符串必须是连接在一起的。比如A和B的公共子字符串是“def”。

求解最长公共子序列要用到动态规划的概念。我们用c[i][j]记录X[i]与Y[j] 的LCS 的长度,那么在计算c[i,j]之前,c[i-1][j-1],c[i-1][j]与c[i][j-1]均已计算出来。此时我们根据X[i] = Y[j]还是X[i] != Y[j],就可以计算出c[i][j]。问题的递归式写成:

在经典的算法导论那本书里,文章使用了b[][]来记录c[i,j] 选自于哪一个(从递归式里,我们知道有三个不同的选择),但是,我们可以不借助于数组b而借助于数组c本身临时判断c[i,j]的值是由c[i-1,j-1],c[i-1,j]和c[i,j-1]中哪一个数值元素所确定,原理是通过我们如何选取c[i,j]来决定的。 在代码里面,我们可以看得出,代码行14,15对应打印的代码行31,32, 代码行17对应打印打印行的36到40。

代码如下:

[java] view plaincopy
  1. public static int[][] LCS(String str1, String str2) {  
  2.         int[][] opt = new int[str2.length() + 1][str1.length() + 1];  
  3.           
  4.         for (int i = 0; i <= str2.length(); i++) {  
  5.             opt[i][0] = 0;  
  6.         }  
  7.           
  8.         for (int j = 0; j <= str1.length(); j++) {  
  9.             opt[0][j] = 0;  
  10.         }  
  11.           
  12.         for (int j = 1; j <= str1.length(); j++) {  
  13.             for (int i = 1; i <= str2.length(); i++) {  
  14.                 if (str2.charAt(i-1) == str1.charAt(j-1)) {  
  15.                     opt[i][j] = opt[i-1][j-1] + 1;  
  16.                 } else {  
  17.                     opt[i][j] = ( opt[i-1][j] >= opt[i][j-1] ? opt[i-1][j] : opt[i][j-1]);  
  18.                 }  
  19.             }  
  20.         }  
  21.           
  22.         return opt;  
  23.     }  
  24.       
  25.     public static void print(int[][] opt, String X, String Y, int i, int j) {  
  26.           
  27.         if (i == 0 || j == 0) {  
  28.             return;  
  29.         }  
  30.           
  31.         if (X.charAt(i - 1) == Y.charAt(j - 1)) {  
  32.                        System.out.print(X.charAt(i - 1));     
  33.                        print(opt, X, Y, i - 1, j - 1);  // don't put this line before the upper line. Otherwise, the order is wrong.  
  34.                 }else if (opt[i - 1][j] >= opt[i][j]) {  
  35.                        print(opt, X, Y, i - 1, j);  
  36.                 } else {  
  37.                        print(opt, X, Y, i, j - 1);}  
  38.  }  
0 0
原创粉丝点击