题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
import java.util.*; import java.util.stream.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); scanner.useDelimiter("\n"); while (scanner.hasNext()) { String S = scanner.next(); String T = scanner.next(); if (S.equals(T)) { System.out.println(S); continue; } else if (S.contains(T)) { System.out.println(T); continue; } else if (T.contains(S)) { System.out.println(S); continue; } //List<String> list = new ArrayList<>(); HashMap<Integer, String> hashMap = new HashMap<>(); String shortS = S.length()>=T.length()?T:S; String longS = S.length()<T.length()?T:S; int max = shortS.length(); while (max-->0) { int left = 0; int right = max-left-1; //if (!list.isEmpty()) break; if (!hashMap.isEmpty()) break; while (right<longS.length()) { if (shortS.contains(longS.substring(left, right+1))) { //list.add(longS.substring(left, right+1)); hashMap.put(shortS.indexOf(longS.substring(left, right+1)), longS.substring(left, right+1)); } left++; right++; } } Optional<Map.Entry<Integer, String>> min = hashMap.entrySet().stream().min(Map.Entry.comparingByKey()); System.out.println(min.get().getValue()); } } }