1. 题目
读题
考查点
同 HJ65 查找两个字符串a,b中的最长公共子串
2. 解法
思路
代码逻辑
具体实现
自行实现
public class HJ075 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(dp(sc.nextLine(), sc.nextLine()));
}
public static int dp(String str1, String str2) {
int m = str1.length();
int n = str2.length();
int[][] dp = new int[m][n];
int maxLen = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 && j == 0) {
dp[i][j] = str1.charAt(0) == str2.charAt(0) ? 1 : 0;
} else if (i == 0) {
dp[i][j] = str1.charAt(0) == str2.charAt(j) ? 1 : 0;
} else if (j == 0) {
dp[i][j] = str1.charAt(i) == str2.charAt(0) ? 1 : 0;
} else {
if (str1.charAt(i) == str2.charAt(j)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = 0;
}
}
if (dp[i][j] > maxLen) {
maxLen = dp[i][j];
}
}
}
return maxLen;
}
}