题解 | #公共子串计算#
公共子串计算
https://www.nowcoder.com/practice/98dc82c094e043ccb7e0570e5342dd1b
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
String str1 = in.nextLine();
String str2 = in.nextLine();
int length = findMaxLength(str1, str2);
System.out.println(length); // 输出应为 6
}
}
public static int findMaxLength(String str1, String str2) {
int m = str1.length();
int n = str2.length();
// 创建一个二维数组来存储中间结果
int[][] dp = new int[m + 1][n + 1];
int maxLength = 0; // 最大公共子串的长度
// 遍历两个字符串
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
// 如果当前字符相等,则更新dp[i][j]为左上角元素加1
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
// 更新最大长度
maxLength = Math.max(maxLength, dp[i][j]);
}
}
}
return maxLength;
}
}
查看15道真题和解析