From adcef0c89d8aff1114fb778816cd581ec6bd4fef Mon Sep 17 00:00:00 2001 From: "guangxin.yuan" Date: 2025年5月22日 18:26:21 +0800 Subject: [PATCH] update --- .../Solution.java" | 35 ++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git "a/src/345円212円250円346円200円201円350円247円204円345円210円222円/q1143_346円234円200円351円225円277円345円205円254円345円205円261円345円255円220円345円272円217円345円210円227円/Solution.java" "b/src/345円212円250円346円200円201円350円247円204円345円210円222円/q1143_346円234円200円351円225円277円345円205円254円345円205円261円345円255円220円345円272円217円345円210円227円/Solution.java" index 8225a50..9f55848 100644 --- "a/src/345円212円250円346円200円201円350円247円204円345円210円222円/q1143_346円234円200円351円225円277円345円205円254円345円205円261円345円255円220円345円272円217円345円210円227円/Solution.java" +++ "b/src/345円212円250円346円200円201円350円247円204円345円210円222円/q1143_346円234円200円351円225円277円345円205円254円345円205円261円345円255円220円345円272円217円345円210円227円/Solution.java" @@ -2,7 +2,7 @@ /** * 动态规划 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 int longestCommonSubsequence(String text1, String text2) { } 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); + } }

AltStyle によって変換されたページ (->オリジナル) /