题解 | 公共子串计算
公共子串计算
https://www.nowcoder.com/practice/98dc82c094e043ccb7e0570e5342dd1b
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String a = in.nextLine();
String b = in.nextLine();
String s1 = a.length() < b.length() ? a : b;
String s2 = a.length() > b.length() ? a : b;
if (a.length() == 0 || b.length() == 0 || a.length() == 1 && b.length() == 1 &&
!a.equals(b)) {
System.out.println(0);
return;
}
int n = 0;
for (int i = 0; i < s1.length(); i++) {
for (int j = s1.length(); j > i; j--) {
if (s2.contains(s1.substring(i, j))) {
n = j - i > n ? j - i : n;
break;
}
}
}
System.out.println(n);
}
}
查看30道真题和解析
