Skip to content

Commit 837e2ff

Browse files
committed
1143.最长公共子序列
1 parent 5fe8d44 commit 837e2ff

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

1143. 最长公共子序列.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* 动态规划算法之 -- 最长公共子序列
3+
* @param {string} text1
4+
* @param {string} text2
5+
* @return {number}
6+
*/
7+
var longestCommonSubsequence = function (text1, text2) {
8+
let m = text1.length
9+
let n = text2.length
10+
let dp = Array.from(new Array(m + 1), () => new Array(n + 1).fill(0))
11+
12+
for (let i = 0; i < m; i++) {
13+
for (let j = 0; j < n; j++) {
14+
if (text1[i] === text2[j]) {
15+
dp[i + 1][j + 1] = dp[i][j] + 1
16+
} else {
17+
dp[i + 1][j + 1] = Math.max(dp[i + 1][j], dp[i][j + 1])
18+
}
19+
}
20+
}
21+
return dp[m][n]
22+
}
23+
24+
let lcs = longestCommonSubsequence('abc', 'acbd')
25+
// let lcs = longestCommonSubsequence("ezupkr", "ubmrapg")
26+
// let lcs = longestCommonSubsequence("bsbininm", "jmjkbkjkv")
27+
28+
console.log('lcs: ', lcs)

0 commit comments

Comments
 (0)