Skip to content

Commit d5373fd

Browse files
committed
Feat: 1143. Longest Common Subsequence
1 parent 7561b4e commit d5373fd

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* https://leetcode.com/problems/longest-common-subsequence
3+
* T.C. O(m * n)
4+
* S.C. O(n)
5+
*/
6+
function longestCommonSubsequence(text1: string, text2: string): number {
7+
const dp = Array.from({ length: text2.length + 1 }, () => 0);
8+
9+
for (let i = 1; i <= text1.length; i++) {
10+
let prev = 0;
11+
for (let j = 1; j <= text2.length; j++) {
12+
const temp = dp[j];
13+
if (text1[i - 1] === text2[j - 1]) {
14+
dp[j] = prev + 1;
15+
} else {
16+
dp[j] = Math.max(dp[j], dp[j - 1]);
17+
}
18+
prev = temp;
19+
}
20+
}
21+
22+
return dp[text2.length];
23+
}

0 commit comments

Comments
 (0)