题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[]args) {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String a, b;
try {
a = r.readLine();
b = r.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
char[] chs1 = a.toCharArray();
char[] chs2 = b.toCharArray();
char[] mid;
int h1 = chs1.length, h2 = chs2.length, max = 0, start = 0, i = 0, j, k;
if (h1 > h2) {
mid = chs1;
chs1 = chs2;
chs2 = mid;
}
h1 = chs1.length;
h2 = chs2.length;
System.out.println(longString(chs1, chs2, h1 + 1, h2 + 1));
}
// 动态规划
public static String longString(char[] chs1, char[] chs2, int m, int n) {
// 表示在较短字符串str1以第i个字符结尾,str2中以第j个字符结尾时的公共子串长度。
int[][] dp = new int[m][n];
// 匹配字符,并记录最大值的str1的结尾下标
int max = 0;
int index = 0;
// 从左向右递推,i为短字符串str1的结尾索引,j为str2的结尾索引
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (chs1[i - 1] == chs2[j - 1]) {
// 相等则计数
dp[i][j] = dp[i - 1][j - 1] + 1;
// 不断更新变量
if (dp[i][j] > max) {
max = dp[i][j];
index = i;
}
}
}
}
// 截取最大公共子串
return new String(chs1, index - max, max);
}
}