public class Test {
public static void main(String[] args) {
String s1 = "AABdCDEF";
String s2 = "aaaABdCD";
Result result = maxSameSubString(s1, s2);
System.out.println(result);
}
public static Result maxSameSubString(String s1, String s2) {
if (s1 == null || s2 == null || s1.isEmpty() || s2.isEmpty()) {
return new Result(0, 0, 0);
}
int length1 = s1.length();
int length2 = s2.length();
//tem数组用于保存在指定两个字符串特定位置之前已有相同的长度
//例如s1为ABC,s2为AABC,那么对于tem[2][3],保存的值应该是3,因为在s1的第2和s2的第3位之前相同的有A、B,长度为2,再加上相同的C,就是3
int[][] tem = new int[length1][length2];
int start1 = -1;
int start2 = -1;
int maxLength = 0;
for (int i = 0; i < length1; i++) {
//
tem[i][0] = s1.charAt(i) == s2.charAt(0) ? 1 : 0;
for (int j = 0; j < length2; j++) {
tem[0][j] = (s1.charAt(0) == s2.charAt(j) ? 1 : 0);
if (i > 0 && j > 0) {
//如果字符串s1第i和s2的第j位相同,那么截止这两字符串的i和j位置之前相同的最大长度就是s1第i-1和s2的第j-1位再加1
tem[i][j] = s1.charAt(i) == s2.charAt(j)? tem[i - 1][j - 1] + 1 : 0;
}
if (tem[i][j] > maxLength) {
maxLength = tem[i][j];
start1 = i - maxLength + 1;
start2 = j - maxLength + 1;
}
}
}
return new Result(start1, start2, maxLength);
}
static class Result {
int startA;
int startB;
int maxLength;
public Result() {
}
public Result(int startA, int startB, int maxLength) {
super();
this.startA = startA;
this.startB = startB;
this.maxLength = maxLength;
}
@Override
public String toString() {
return "startA:" + startA + "\n" + "startB:" + startB + "\n" + "maxLength:" + maxLength + "\n";
}
}
}
例子的运行结果,最大公共子串为ABdCD