File tree Expand file tree Collapse file tree 1 file changed +34
-1
lines changed Expand file tree Collapse file tree 1 file changed +34
-1
lines changed Original file line number Diff line number Diff line change 2
2
3
3
/**
4
4
* 动态规划 dp[i + 1][j + 1] = Math.max(dp[i+1][j], dp[i][j+1]) o(m*n)
5
- *
5
+ * <p>
6
6
* 若题目为最长公共子串,则在c1,c2不相等时不做处理(赋值0),在遍历过程中记录最大值即可
7
7
*/
8
8
public class Solution {
@@ -25,4 +25,37 @@ public int longestCommonSubsequence(String text1, String text2) {
25
25
}
26
26
return dp [m ][n ];
27
27
}
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
+ }
28
61
}
You can’t perform that action at this time.
0 commit comments