实现如下:
public static void main(String[] args) { String squence1 = "ABCBDAB"; String squence2 = "BDCABC"; int len1 = squence1.length(), len2 = squence2.length(); if (len1 <= 0 || len2 <= 0) { System.out.println("empty squence!"); return; } int[][] allCommonSubLen = new int[len1+1][len2+1]; //print all sub-squences String subSquence = ""; //初始化i=0, j=0 for (int i = 0; i < len1; i++) { allCommonSubLen[i][0] = 0; } for (int j = 0; j < len2; j++) { allCommonSubLen[0][j] = 0; } //迭代关系 for (int i = 1; i <= len1; i++) { for (int j = 1; j <= len2; j++) { char c1 = squence1.charAt(i-1); char c2 = squence2.charAt(j-1); if (c1 == c2) { //subSquence += c1; allCommonSubLen[i][j] = allCommonSubLen[i-1][j-1] + 1; //System.out.println("i="+i+" ; j="+j+" ; subSquence="+subSquence); } else { allCommonSubLen[i][j] = Math.max(allCommonSubLen[i-1][j], allCommonSubLen[i][j-1]); if (allCommonSubLen[i][j] == allCommonSubLen[i-1][j]) { //subSquence += c2; //System.out.println("i="+i+" ; j="+j+" ; subSquence="+subSquence); } else { //subSquence += c1; //System.out.println("i="+i+" ; j="+j+" ; subSquence="+subSquence); } } } } //System.out.println(allCommonSubLen[len1][len2]); }