import java.util.ArrayList; import java.util.List; //use lcs get the max substring of two string o(m+n) str1 and str2 no order relation public class LcsString { public static List<String> getLCSring(final String str1, final String str2) { if("".equals(str1.trim())||str1==null||"".equals(str1.trim())||str1==null) return new ArrayList<String>(); List<String> list = new ArrayList<String>(); if(str1.contains(str2)){ list.add(str2); return list; }else if(str2.contains(str1)){ list.add(str1); return list; } Integer len1 = str1.length(); Integer len2 = str2.length(); Integer[][] arrayIntegers = new Integer[len1][len2]; int[] maxIntegers = new int[len1]; int max = 0; for (int i = 0; i < len1; i++) { for (int j = 0; j < len2; j++) { if (str1.charAt(i) == str2.charAt(j)) { if (i == 0 || j == 0) { max = max <= 1 ? 1 : max; arrayIntegers[i][j] = 1; } else { arrayIntegers[i][j] = arrayIntegers[i - 1][j - 1] + 1; max = max < arrayIntegers[i][j] ? arrayIntegers[i][j] : max; } maxIntegers[i] = arrayIntegers[i][j]; } else { arrayIntegers[i][j] = 0; } } } for (int i = 0; i < maxIntegers.length; i++) { if (maxIntegers[i] == max) { list.add(str1.substring(i - max + 1, i + 1)); } } return list; } }
//str1和str2谁长谁短都一样
public static List<String> getLCSring(final String str1, final String str2) { List<String> list = new ArrayList<String>(); Integer len1 = str1.length(); Integer len2 = str2.length(); Integer[][] arrayIntegers = new Integer[len1][len2];
//记录多个最长子串的位置和长度 int[] maxIntegers = new int[len1];
//记录最长子串长度 int max = 0; for (int i = 0; i < len1; i++) { for (int j = 0; j < len2; j++) { if (str1.charAt(i) == str2.charAt(j)) { if (i == 0 || j == 0) { max = max <= 1 ? 1 : max; arrayIntegers[i][j] = 1; } else { arrayIntegers[i][j] = arrayIntegers[i - 1][j - 1] + 1; max = max < arrayIntegers[i][j] ? arrayIntegers[i][j] : max; } maxIntegers[i] = arrayIntegers[i][j]; } else { arrayIntegers[i][j] = 0; } } } for (int i = 0; i < maxIntegers.length; i++) {
//返回各个子串 if (maxIntegers[i] == max) { list.add(str1.substring(i - max + 1, i + 1)); } } return list; }
算法:LCS算法
俗称矩形算法
横纵坐标相同的记为1 不同的记为0 最后对角线1最多的就是最长的子串(线性代数啊) 为了程序方便,用一个二维数组记录,如果斜上角的不为1,该坐标位置的数就是斜上角的数加1.最后不管是哪个字符串都可以取到公共字符串