Skip to content

Commit 471cb16

Browse files
committed
longest common subsequence solution
1 parent b7ff251 commit 471cb16

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
function longestCommonSubsequence(text1: string, text2: string): number {
2+
const m = text1.length;
3+
const n = text2.length;
4+
5+
const dp: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
6+
7+
for (let i = 1; i <= m; i++) {
8+
for (let j = 1; j <= n; j++) {
9+
if (text1[i - 1] === text2[j - 1]) {
10+
dp[i][j] = dp[i - 1][j - 1] + 1;
11+
} else {
12+
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
13+
}
14+
}
15+
}
16+
17+
return dp[m][n];
18+
}

0 commit comments

Comments
 (0)