题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
import java.util.Scanner; public class Main { // abcdefghijklmnop // abcsafjklmnopqrstuvw public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { String a = in.nextLine(); String b = in.nextLine(); int longLength = 0; int shortLength = 0; String origin = null; String model = null; if (b.length() > a.length()) { shortLength = a.length(); longLength = b.length(); origin = b; model = a; } else { shortLength = b.length(); longLength = a.length(); origin = a; model = b; } int max = 0; String result = ""; for (int j = 0; j < shortLength; j++) { // 逐个匹配 for (int i = 0; i < longLength; i++) { int temp = 0; int y = i, z = j; while (y < longLength && z < shortLength) { if (origin.charAt(y) == model.charAt(z)) { temp++; z++; y++; } else { break; } } if (temp > max) { result = model.substring(j, j + temp); max = temp; } } } System.out.println(result); } } }