最长公共子序列Java代码实现
生活随笔
收集整理的這篇文章主要介紹了
最长公共子序列Java代码实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最長公共子序列定義:兩個或多個已知數列的子序列集合中最長的就是最長公共子序列。
比如數列A = “abcdef”和B = “adefcb”,那么兩個數列的公共子序列集合有{”a","ab","abc","adef",等等},其中最長的就是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]子問題來求解,依次遞堆到最小子問題,動態規劃的遞歸式描述為:
計算c[i][j]矩陣,利用矩陣可以輸出最長公共子序列字符,具體代碼如下:
package cn.hm;public class LongestCommonSub {public static void main(String[] args) {// TODO Auto-generated method stubString str1 = "fjssharpsword";String str2 = "helloworld";//計算lcs遞歸矩陣int[][] re = longestCommonSubsequence(str1, str2);//打印矩陣for (int i = 0; i <= str1.length(); i++) {for (int j = 0; j <= str2.length(); j++) {System.out.print(re[i][j] + " ");}System.out.println();}System.out.println();System.out.println();//輸出LCSprint(re, str1, str2, str1.length(), str2.length());}// 假如返回兩個字符串的最長公共子序列的長度public static int[][] longestCommonSubsequence(String str1, String str2) {int[][] matrix = new int[str1.length() + 1][str2.length() + 1];//建立二維矩陣// 初始化邊界條件for (int i = 0; i <= str1.length(); i++) {matrix[i][0] = 0;//每行第一列置零}for (int j = 0; j <= str2.length(); j++) {matrix[0][j] = 0;//每列第一行置零}// 填充矩陣for (int i = 1; i <= str1.length(); i++) {for (int j = 1; j <= str2.length(); j++) {if (str1.charAt(i - 1) == str2.charAt(j - 1)) {matrix[i][j] = matrix[i - 1][j - 1] + 1;} else {matrix[i][j] = (matrix[i - 1][j] >= matrix[i][j - 1] ? matrix[i - 1][j]: matrix[i][j - 1]);}}}return matrix;}//根據矩陣輸出LCSpublic static void print(int[][] opt, String X, String Y, int i, int j) {if (i == 0 || j == 0) {return;}if (X.charAt(i - 1) == Y.charAt(j - 1)) {print(opt, X, Y, i - 1, j - 1);System.out.print(X.charAt(i - 1));} else if (opt[i - 1][j] >= opt[i][j]) {print(opt, X, Y, i - 1, j);} else {print(opt, X, Y, i, j - 1);}} }
輸出結果如下:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 2 2 2 0 1 1 1 1 1 1 1 2 2 2 0 1 1 1 1 1 1 1 2 2 2 0 1 1 1 1 1 2 2 2 2 2 0 1 1 1 1 2 2 3 3 3 3 0 1 1 1 1 2 2 3 4 4 4 0 1 1 1 1 2 2 3 4 4 5 hword通過代碼的步驟去理解動態規劃的最有子結構以及遞歸解性質,再而理解最長公共子序列是如何通過矩陣來輸出。
總結
以上是生活随笔為你收集整理的最长公共子序列Java代码实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MapReduce基础开发context
- 下一篇: Java工程中使用Log4j小记