题解 | #最长公共子串# DP
最长公共子串
https://www.nowcoder.com/practice/f33f5adc55f444baa0e0ca87ad8a6aac
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* longest common substring
* @param str1 string字符串 the string
* @param str2 string字符串 the string
* @return string字符串
*/
public String LCS (String str1, String str2) {
// write code here
int len1 = str1.length();
int len2 = str2.length();
int dp[][] = new int[len1+1][len2+1];
int max = 0;
int max_i = 0, max_j = 0;
for(int i=1;i<=len1;i++){
for(int j=1;j<=len2;j++){
if(str1.charAt(i-1) == str2.charAt(j-1)){
dp[i][j] = dp[i-1][j-1] + 1;
}else{
dp[i][j] = 0;
}
if(dp[i][j] > max){
max = dp[i][j];
max_i = i;
max_j = j;
}
}
}
return str1.substring(max_i - max , max_i );
}
}
通用的最长公共子串解法中,求解的是最长公共子串的长度,我们可以同时记录下来,获取到最大长度时候的下标,然后进行截取,该方法只适用于最长公共子串(连续),对于最长公共子序列(不连续)不成立。
查看9道真题和解析