Skip to content

Commit 37a35e4

Browse files
committed
feat: 1143. Longest Common Subsequence
1 parent 324ffa7 commit 37a35e4

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// n: len(text1), m: len(text2)
2+
// Time complexity: O(n * m)
3+
// Space complexity: O(n * m)
4+
5+
/**
6+
* @param {string} text1
7+
* @param {string} text2
8+
* @return {number}
9+
*/
10+
var longestCommonSubsequence = function (text1, text2) {
11+
const n = text1.length;
12+
const m = text2.length;
13+
14+
const dp = Array.from({ length: n + 1 }, () =>
15+
Array.from({ length: m + 1 }, () => 0)
16+
);
17+
18+
for (let i = 1; i <= n; i++) {
19+
for (let j = 1; j <= m; j++) {
20+
if (text1[i - 1] === text2[j - 1]) {
21+
dp[i][j] = dp[i - 1][j - 1] + 1;
22+
continue;
23+
}
24+
25+
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
26+
}
27+
}
28+
29+
return dp.at(-1).at(-1);
30+
};

0 commit comments

Comments
 (0)