Skip to content

Commit 6fda5a7

Browse files
committed
longest-common-subsequence solution
1 parent 9e34767 commit 6fda5a7

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* https://leetcode.com/problems/longest-common-subsequence/submissions/1644426037/
3+
* @param {string} text1
4+
* @param {string} text2
5+
* @return {number}
6+
*/
7+
var longestCommonSubsequence = function (text1, text2) {
8+
const m = text1.length;
9+
const n = text2.length;
10+
11+
// Create 2D array initialized with 0
12+
const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
13+
14+
// Fill the dp table
15+
for (let i = 1; i <= m; i++) {
16+
for (let j = 1; j <= n; j++) {
17+
if (text1[i - 1] === text2[j - 1]) {
18+
// Characters match
19+
dp[i][j] = dp[i - 1][j - 1] + 1;
20+
} else {
21+
// No match, take the max from left or top cell
22+
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
23+
}
24+
}
25+
}
26+
27+
// The length of the longest common subsequence
28+
return dp[m][n];
29+
};

0 commit comments

Comments
 (0)