最长公共子串
public static String lcStr(String s1, String s2) { int len1 = s1.length(); int len2 = s2.length(); int max = 0; //flag 表示最长功能子串起始位置 int flag = -1; if (len1 == 0 || len2 == 0) { return ""; } //为了初始化方便 使用了n+1个空间 result[i][j]表示包含i j两个元素最长公共子串的最长长度 int[][] result = new int[len1 + 1][len2 + 1]; for (int i = 0; i < len1; i++) { result[i][0] = 0; } for (int i = 0; i < len2; i++) { result[0][i] = 0; } //显然对于s1(i),s2(j)只有两种情况 for (int i = 0; i < len1; i++) { for (int j = 0; j < len2; j++) { if (s1.charAt(i) == s2.charAt(j)) { result[i + 1][j + 1] = result[i][j] + 1; } else { result[i + 1][j + 1] = 0; } if (max < result[i + 1][j + 1]) { max = result[i + 1][j + 1]; flag = i - max + 1; } } } return s1.substring(flag, flag + max); }