1. 题目
读题
考查点
2. 解法
思路
代码逻辑
具体实现
自行实现
public class HJ065 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(dp(sc.nextLine(), sc.nextLine()));
}
public static String dp(String str1, String str2) {
if (str1.length() > str2.length()) {
String temp = str1;
str1 = str2;
str2 = temp;
}
int m = str1.length();
int n = str2.length();
int[][] dp = new int[m][n];
int maxLen = 0;
int index = 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];
index = i;
}
}
}
return str1.substring(index - maxLen + 1, index + 1);
}
}