|
| 1 | +// TC: O(m * n) |
| 2 | +// SC: O(m * n) |
| 3 | +function longestCommonSubsequence(text1: string, text2: string): number { |
| 4 | + const memo = new Map<string, number>(); |
| 5 | + |
| 6 | + const dfs = (i: number, j: number) => { |
| 7 | + const key = `${i}-${j}`; |
| 8 | + |
| 9 | + if (memo.has(key)) return memo.get(key); |
| 10 | + |
| 11 | + if (i === text1.length || j === text2.length) { |
| 12 | + // "" |
| 13 | + memo.set(key, 0); |
| 14 | + } else if (text1[i] === text2[j]) { |
| 15 | + memo.set(key, 1 + dfs(i + 1, j + 1)!); |
| 16 | + } else { |
| 17 | + memo.set(key, Math.max(dfs(i + 1, j)!, dfs(i, j + 1)!)); |
| 18 | + } |
| 19 | + |
| 20 | + return memo.get(key); |
| 21 | + }; |
| 22 | + |
| 23 | + return dfs(0, 0)!; |
| 24 | +} |
| 25 | + |
| 26 | + |
| 27 | +// TC: O(m * n) |
| 28 | +// SC: O(m * n) |
| 29 | +// function longestCommonSubsequence(text1: string, text2: string): number { |
| 30 | +// const m = text1.length + 1; |
| 31 | +// const n = text2.length + 1; |
| 32 | + |
| 33 | +// const dp: number[][] = Array.from({ length: m }, () => Array(n).fill(0)); |
| 34 | + |
| 35 | +// for (let i = 1; i < m; i++) { |
| 36 | +// for (let j = 1; j < n; j++) { |
| 37 | +// // Note: text1[i - 1] and text2[j - 1] because dp uses 1-based indexing, |
| 38 | +// // while the strings use 0-based indexing |
| 39 | +// if (text1[i - 1] === text2[j - 1]) { |
| 40 | +// dp[i][j] = 1 + dp[i - 1][j - 1]; |
| 41 | +// } else { |
| 42 | +// dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); |
| 43 | +// } |
| 44 | +// } |
| 45 | +// } |
| 46 | + |
| 47 | +// return dp[m - 1][n - 1]; |
| 48 | +// } |
0 commit comments