题解 | #公共子串计算#
公共子串计算
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); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { // 注意 while 处理多个 case String a = in.nextLine(); String b = in.nextLine(); //提高效率筛选长短 注意三元运算符后半部分的顺序 String short_ = a.length() > b.length() ? b : a; String long_ = a.length() > b.length() ? a : b; boolean hasResult = false; for (int length = short_.length(); length > 0; length--) { //length是子串长度 i是步长 for (int i = 0; i < short_.length() - length + 1; i++) { if (long_.contains(short_.substring(i, i + length))) { System.out.print(length); hasResult = true; break; } } if (hasResult) { break; } } if (!hasResult) { System.out.print(0); } } } }