From adcef0c89d8aff1114fb778816cd581ec6bd4fef Mon Sep 17 00:00:00 2001 From: "guangxin.yuan" Date: Thu, 22 May 2025 18:26:21 +0800 Subject: [PATCH] update --- .../q1143_最长公共子序列/Solution.java | 35 ++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/src/动态规划/q1143_最长公共子序列/Solution.java b/src/动态规划/q1143_最长公共子序列/Solution.java index 8225a50..9f55848 100644 --- a/src/动态规划/q1143_最长公共子序列/Solution.java +++ b/src/动态规划/q1143_最长公共子序列/Solution.java @@ -2,7 +2,7 @@ package 动态规划.q1143_最长公共子序列; /** * 动态规划 dp[i + 1][j + 1] = Math.max(dp[i+1][j], dp[i][j+1]) o(m*n) - * + *

* 若题目为最长公共子串,则在c1,c2不相等时不做处理(赋值0),在遍历过程中记录最大值即可 */ public class Solution { @@ -25,4 +25,37 @@ public class Solution { } return dp[m][n]; } + + /** + * 最长公共字串 + * + * @param str1 + * @param str2 + * @return + */ + public static String longestCommonSubstring(String str1, String str2) { + int m = str1.length(); + int n = str2.length(); + int[][] dp = new int[m + 1][n + 1]; + int maxLength = 0; + int endIndex = -1; + + for (int i = 1; i <= m; i++) { + for (int j = 1; j <= n; j++) { + if (str1.charAt(i - 1) == str2.charAt(j - 1)) { + dp[i][j] = dp[i - 1][j - 1] + 1; + if (dp[i][j] > maxLength) { + maxLength = dp[i][j]; + endIndex = i - 1; + } + } else { + dp[i][j] = 0; + } + } + } + if (maxLength == 0) { + return ""; + } + return str1.substring(endIndex - maxLength + 1, endIndex + 1); + } }