题解 | #最长公共子串#
最长公共子串
https://www.nowcoder.com/practice/f33f5adc55f444baa0e0ca87ad8a6aac?tpId=117&tags=&title=&difficulty=0&judgeStatus=0&rp=1
/**
* longest common substring
* @param str1 string字符串 the string
* @param str2 string字符串 the string
* @return string字符串
*/
function LCS( str1 , str2 ) {
const dp = new Array(str1.length + 1);
let max = 0;
const map = new Map()
for (let i = 0; i <= str1.length; i++) { // 初始化整个dp矩阵,每个值为0
dp[i] = new Array(str2.length + 1).fill(0);
}
for(let i = 1;i<=str1.length;i++){
for(let j = 1;j<=str2.length;j++){
if(str1[i-1] === str2[j-1]){
dp[i][j] = dp[i - 1][j - 1] + 1
max = Math.max(max,dp[i][j])
if(!map.has(max)) map.set(max,i) //避免重复
}
}
}
let startIndex = map.get(max) - max;
let endIndex = map.get(max) ;
return str1.substring(startIndex,endIndex) //截取字符串
}
module.exports = {
LCS : LCS
};