题解 | 最长公共子串
最长公共子串
https://www.nowcoder.com/practice/f33f5adc55f444baa0e0ca87ad8a6aac
import java.util.*; public class Solution { /** * 最长公共子串, 动态规划 * 定义 dp[i][j]表示以 str1[i] 和 str2[j] 结尾的最长公共子串的长度, * 如果str1[i] != str2[j], 那么 dp[i][j] = 0; 否则 dp[i][j] = dp[i-1][j-1] + 1; * 在计算的过程中记录最大公共子串的长度,并记录最大子串的结束位置 */ public String LCS(String str1, String str2) { int[][] dp = new int[str1.length() + 1][str2.length() + 1]; int maxLen = 0; int end = 0; for (int i = 0; i < str1.length(); i++) { for (int j = 0; j < str2.length(); j++) { if (str1.charAt(i) == str2.charAt(j)) { dp[i + 1][j + 1] = dp[i][j] + 1; if (dp[i + 1][j + 1] > maxLen) { maxLen = dp[i + 1][j + 1]; end = i + 1; } } else { dp[i + 1][j + 1] = 0; } } } return str1.substring(end - maxLen, end); } }