Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit adcef0c

Browse files
author
guangxin.yuan
committed
update
1 parent 7f426cc commit adcef0c

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

‎src/动态规划/q1143_最长公共子序列/Solution.java

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
/**
44
* 动态规划 dp[i + 1][j + 1] = Math.max(dp[i+1][j], dp[i][j+1]) o(m*n)
5-
*
5+
* <p>
66
* 若题目为最长公共子串,则在c1,c2不相等时不做处理(赋值0),在遍历过程中记录最大值即可
77
*/
88
public class Solution {
@@ -25,4 +25,37 @@ public int longestCommonSubsequence(String text1, String text2) {
2525
}
2626
return dp[m][n];
2727
}
28+
29+
/**
30+
* 最长公共字串
31+
*
32+
* @param str1
33+
* @param str2
34+
* @return
35+
*/
36+
public static String longestCommonSubstring(String str1, String str2) {
37+
int m = str1.length();
38+
int n = str2.length();
39+
int[][] dp = new int[m + 1][n + 1];
40+
int maxLength = 0;
41+
int endIndex = -1;
42+
43+
for (int i = 1; i <= m; i++) {
44+
for (int j = 1; j <= n; j++) {
45+
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
46+
dp[i][j] = dp[i - 1][j - 1] + 1;
47+
if (dp[i][j] > maxLength) {
48+
maxLength = dp[i][j];
49+
endIndex = i - 1;
50+
}
51+
} else {
52+
dp[i][j] = 0;
53+
}
54+
}
55+
}
56+
if (maxLength == 0) {
57+
return "";
58+
}
59+
return str1.substring(endIndex - maxLength + 1, endIndex + 1);
60+
}
2861
}

0 commit comments

Comments
(0)

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