题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
package org.example.test.practice.third; import java.io.IOException; import java.util.Scanner; public class Main { /** * nvlrzqcjltmrejybjeshffenvkeqtbsnlocoyaokdpuxutrsmcmoearsgttgyyucgzgcnurfbubgvbwpyslaeykqhaaveqxijc * wkigrnngxehuiwxrextitnmjykimyhcbxildpnmrfgcnevjyvwzwuzrwvlomnlogbptornsybimbtnyhlmfecscmojrxekqmj * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNext()) { // 注意 while 处理多个 case String a = in.nextLine(); String b = in.nextLine(); int max = 0; String ans=""; if (a.length()<b.length()) { int[][] dp = new int[a.length() + 1][b.length() + 1]; for (int i = 1; i <= a.length(); i++) { for (int j = 1; j <= b.length(); j++) { if (a.charAt(i - 1) == b.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1] + 1; if (dp[i][j] > max) { ans = a.substring(i - dp[i][j], i); max = dp[i][j]; } } } } }else { int[][] dp = new int[b.length() + 1][a.length() + 1]; for (int i = 1; i <= b.length(); i++) { for (int j = 1; j <= a.length(); j++) { if (b.charAt(i - 1) == a.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1] + 1; if (dp[i][j] > max) { ans = b.substring(i - dp[i][j], i); max = dp[i][j]; } } } } } System.out.println(ans); } } }