题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
import java.util.Scanner; // 两层for循环,遍历所有子串 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s1 = in.nextLine(); String s2 = in.nextLine(); String sortS = s1; String longS = s2; String res = ""; if (s1.length() > s2.length()) { sortS = s2; longS = s1; } for (int i = 0; i < sortS.length(); i++) { for (int j = 0; j < sortS.length() - i; j++) { if (longS.contains(sortS.substring(i, sortS.length() - j))) { if(sortS.substring(i, sortS.length() - j).length() > res.length()) res = sortS.substring(i, sortS.length() - j); } } } System.out.println(res); } }