题解 | #公共子串计算#
公共子串计算
https://www.nowcoder.com/practice/98dc82c094e043ccb7e0570e5342dd1b
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
String s2 = sc.nextLine();
int res;
if (s1.length() < s2.length()) {
res = method(s1, s2);
} else res = method(s2, s1);
System.out.println(res);
}
private static int method(String shortString, String longString) {
int count = 0;
int res = 0;
for (int i = 0; i < shortString.length(); i++) {
String sub = shortString.substring(i);
for (int j = 0; j < longString.length(); j++) {
int curIndex = j;
for (int k = 0; k < sub.length(); k++) {
if (curIndex >= longString.length()) break;
if (longString.charAt(curIndex) == sub.charAt(k)) {
curIndex++;
count++;
} else break;
}
res = Math.max(count, res);
count = 0;
}
}
return res;
}
}
