(a: string, b: string)
| 1 | export function longestCommonSubsequence(a: string, b: string) { |
| 2 | const lengths: number[][] = []; |
| 3 | for (let i = 0; i <= a.length; i++) { |
| 4 | lengths[i] = []; |
| 5 | for (let j = 0; j <= b.length; j++) { |
| 6 | if (i === 0 || j === 0) { |
| 7 | lengths[i][j] = 0; |
| 8 | } else if (a[i - 1] === b[j - 1]) { |
| 9 | lengths[i][j] = lengths[i - 1][j - 1] + 1; |
| 10 | } else { |
| 11 | lengths[i][j] = Math.max(lengths[i - 1][j], lengths[i][j - 1]); |
| 12 | } |
| 13 | } |
| 14 | } |
| 15 | let result = ""; |
| 16 | let x = a.length; |
| 17 | let y = b.length; |
| 18 | while (x !== 0 && y !== 0) { |
| 19 | if (lengths[x][y] === lengths[x - 1][y]) { |
| 20 | x--; |
| 21 | } else if (lengths[x][y] === lengths[x][y - 1]) { |
| 22 | y--; |
| 23 | } else { |
| 24 | result = a[x - 1] + result; |
| 25 | x--; |
| 26 | y--; |
| 27 | } |
| 28 | } |
| 29 | return result; |
| 30 | } |
no outgoing calls
no test coverage detected