题解 | #公共子串计算#
公共子串计算
https://www.nowcoder.com/practice/98dc82c094e043ccb7e0570e5342dd1b
import java.util.*; 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(maxlengthes(zfc1, zfc2)); } else { System.out.println(maxlengthes(zfc2, zfc1)); } } private static int maxlengthes(String zfc1, String zfc2) { int zfcl1 = zfc1.length(); int zfcl2 = zfc2.length(); int maxlength = 0; int dp[][] = new int[zfcl1 + 1][zfcl2 + 1]; for (int i = 1; i <= zfcl1; i++) { for (int j = 1; j <= zfcl2; j++) { if (zfc1.charAt(i - 1) == zfc2.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1] + 1; maxlength = Math.max(maxlength, dp[i][j]); } } } return maxlength; } }