题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
import java.util.*; import java.math.*; public class Main { public static void main(String[] args) { Scanner fzhinput = new Scanner(System.in); String zfc1 = fzhinput.nextLine(); String zfc2 = fzhinput.nextLine(); if(zfc1.length()<zfc2.length()){ System.out.println(maxzfczc(zfc1, zfc2)); } else{ System.out.println(maxzfczc(zfc2, zfc1)); } } private static String maxzfczc(String zfc1, String zfc2) { int len1 = zfc1.length(); int len2 = zfc2.length(); int maxLength = 0; int endIndex = 0; int[][] dp = new int[len1 + 1][len2 + 1]; for (int i = 1; i <= len1; i++) { for (int j = 1; j <= len2; j++) { if (zfc1.charAt(i - 1) == zfc2.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1] + 1; if (dp[i][j] > maxLength) { maxLength = dp[i][j]; endIndex = i; } } } } return zfc1.substring(endIndex - maxLength, endIndex); } }