一、题目地址
二、思路视频
https://www.bilibili.com/video/BV14A411v7mP?from=search&seid=3658685940490164141
https://www.bilibili.com/video/BV1iE411Y7fy?from=search&seid=14253537371024452159
三、具体代码
/**
* longest common subsequence
* @param s1 string字符串 the string
* @param s2 string字符串 the string
* @return string字符串
*/
function LCS( s1 , s2 ) {
//1、获取s1和s2的长度
let m = s1.length;
let n = s2.length;
//2、定义二维矩阵dp
let dp = Array.from(new Array(m + 1), () => new Array(n + 1).fill(''));
//3、遍历二维矩阵
for(let i=1; i<=m; i++) {
for(let j=1; j<=n; j++) {
if(s1[i-1] === s2[j-1]) {
dp[i][j] = dp[i-1][j-1] + s1[i-1];
}else {
dp[i][j] = dp[i-1][j].length > dp[i][j-1].length ? dp[i-1][j] : dp[i][j-1];
}
}
}
//4、最后还要判断一下dp[m][n]是否为空, 为空返回-1,不为空,返回dp[m][n]
return dp[m][n].length === 0 ? -1 : dp[m][n];
}
module.exports = {
LCS : LCS
};