最大公共子序列 public class LongestCommonSubsequence { public static void main(String[] args) { LongestCommonSubsequence lcs = new LongestCommonSubsequence(); String x = "helloword"; String y = "helloweweqweord"; int[][] c = lcs.lcsLength(x, y); lcs.printLcs(c, x, y, x.length(), y.length()); System.out.println(); for (int i = 0; i < x.length(); i++) { for (int j = 0; j < y.length(); j++) { System.out.print(c[i][j] + " "); } System.out.println(); } } /** * 获得lcs的长度 */ int[][] lcsLength(String x, String y) { int m = x.length(); int n = y.length(); int c[][] = new int[m + 1][n + 1]; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (x.charAt(i - 1) == y.charAt(j - 1)) { c[i][j] = c[i - 1][j - 1] + 1; } else if (c[i - 1][j] >= c[i][j - 1]) { c[i][j] = c[i - 1][j]; } else { c[i][j] = c[i][j - 1]; } } } return c; } /** * 打印lcs */ void printLcs(int c[][], String x,String y, int i, int j) { if (i == 0 || j == 0) { return; } if (x.charAt(i - 1) == y.charAt(j - 1)) { printLcs(c, x, y, i - 1, j - 1); System.out.print(x.charAt(i - 1)); } else if (c[i - 1][j] >= c[i][j]) { printLcs(c, x, y, i - 1, j); } else { printLcs(c, x, y, i, j - 1); } } } <textarea>