题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
这道题不是子序列,所以用两个for循环, 利用String的contain 比较即可.
注意要区分哪个是长字符串,那个是短的字符串,因为可能有多个子字符相同长度
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 shortOne = a.length() > b.length() ? b : a; String longOne = a.length() < b.length() ? b : a; MaxSub maxSub = new MaxSub(0, ""); for (int i = 0; i < shortOne.length(); i++) { for (int j = i + 1; j <= shortOne.length(); j++) { String substring = shortOne.substring(i, j); if (longOne.contains(substring)) { if (maxSub.len < substring.length()) { maxSub.len = substring.length(); maxSub.subString = substring; } } } } System.out.println(maxSub.subString); } } public static class MaxSub { int len; String subString; public MaxSub(int len, String subString) { this.len = len; this.subString = subString; } } }