题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
System.in));
String str;
while ((str = bufferedReader.readLine()) != null) {
String str2 = bufferedReader.readLine();
// 拿到短字串 最先出现的那个最长字串,所以先遍历短字串
if (str.length() < str2.length()) {
getLongSon(str, str2);
} else {
getLongSon(str2, str);
}
}
}
private static void getLongSon(String str, String str2) {
int max = 0;
LinkedHashMap<Integer, Point> lhm = new LinkedHashMap<>();
for (int i = 0; i < str.length(); i++) {
for (int j = 0; j < str2.length(); j++) {
int l = i;
int r = j;
while (l < str.length() && r < str2.length() &&
str.charAt(l) == str2.charAt(r)) {
l++;
r++;
}
// 最后一次不满足条件,l需要回滚
l--;
if (l - i + 1 > max) {
max = l - i + 1;
// 传入l+1方便后面截取
lhm.put(max, new Point(i, l + 1));
}
}
}
Point point = lhm.get(max);
System.out.println(str.substring(point.x, point.y));
}
static class Point {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
}


查看6道真题和解析