master
guangxin.yuan 4 months ago
parent 7f426ccfdf
commit adcef0c89d

@ -2,7 +2,7 @@ package 动态规划.q1143_最长公共子序列;
/** /**
* dp[i + 1][j + 1] = Math.max(dp[i+1][j], dp[i][j+1]) o(m*n) * dp[i + 1][j + 1] = Math.max(dp[i+1][j], dp[i][j+1]) o(m*n)
* * <p>
* c1,c20 * c1,c20
*/ */
public class Solution { public class Solution {
@ -25,4 +25,37 @@ public class Solution {
} }
return dp[m][n]; 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);
}
} }

Loading…
Cancel
Save