题解 | #公共子串计算#
公共子串计算
https://www.nowcoder.com/practice/98dc82c094e043ccb7e0570e5342dd1b
import java.util.Objects;
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
String nextLine = in.nextLine();
if (Objects.isNull(nextLine) || nextLine.equals("")) {
break;
}
String nextLine1 = in.nextLine();
// 先dp找出最长的长度
// aaabc
// baaabbc
int[][] dp = new int[nextLine.length() + 1][nextLine1.length() + 1];
int max = 0;
String maxStr = "";
for (int i = 1; i <= nextLine.length(); i++) {
for (int j = 1; j <= nextLine1.length(); j++) {
// 假设字符串1的第i个字符和字符串2的第j个字符一致,那么他们的最大dp值为 各自当前字符串长度-1后的dp值+1
if (nextLine.charAt(i - 1) == nextLine1.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
if (dp[i][j] > max) {
max = dp[i][j];
maxStr = nextLine1.substring(j - max, j);
}
} else {
// 当发现不等于时,说明断开了,需要从0开始计算,这一步非常关键!
dp[i][j] = 0;
}
}
}
System.out.println(maxStr.length());
}
}
}

