Skip to content

Commit bf47088

Browse files
authored
Update 1143-longest-common-subsequence.js
1 parent c99c670 commit bf47088

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

1143-longest-common-subsequence.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,30 @@ const longestCommonSubsequence = function(text1, text2) {
1515
}
1616
return dp[dp.length - 1].pop()
1717
}
18+
19+
// another
20+
21+
/**
22+
* @param {string} text1
23+
* @param {string} text2
24+
* @return {number}
25+
*/
26+
const longestCommonSubsequence = function(text1, text2) {
27+
const len1 = text1.length
28+
const len2 = text2.length
29+
if(len1 === 0 || len2 === 0) return 0
30+
if(len1 < len2) return longestCommonSubsequence(text2, text1)
31+
const dp = Array(len1 + 1).fill(0)
32+
for(let i = 1; i <= len2; i++) {
33+
let prev = 0
34+
for(let j = 1; j <= len1; j++) {
35+
const tmp = dp[j]
36+
if(text1[j - 1] === text2[i - 1]) dp[j] = Math.max(dp[j], prev + 1)
37+
else {
38+
dp[j] = Math.max(dp[j - 1], dp[j])
39+
}
40+
prev = tmp
41+
}
42+
}
43+
return dp[len1]
44+
};

0 commit comments

Comments
 (0)