|
| 1 | +/** |
| 2 | + * @param {string} s1 |
| 3 | + * @param {string} s2 |
| 4 | + * @return {string} |
| 5 | + */ |
| 6 | +export default function longestCommonSubsequnce(s1, s2) { |
| 7 | + // Init LCS matrix. |
| 8 | + const lcsMatrix = Array(s2.length + 1).fill(null).map(() => Array(s1.length + 1).fill(null)); |
| 9 | + |
| 10 | + // Fill first row with zeros. |
| 11 | + for (let columnIndex = 0; columnIndex <= s1.length; columnIndex += 1) { |
| 12 | + lcsMatrix[0][columnIndex] = 0; |
| 13 | + } |
| 14 | + |
| 15 | + // Fill first column with zeros. |
| 16 | + for (let rowIndex = 0; rowIndex <= s2.length; rowIndex += 1) { |
| 17 | + lcsMatrix[rowIndex][0] = 0; |
| 18 | + } |
| 19 | + |
| 20 | + // Fill rest of the column that correspond to each of two strings. |
| 21 | + for (let rowIndex = 1; rowIndex <= s2.length; rowIndex += 1) { |
| 22 | + for (let columnIndex = 1; columnIndex <= s1.length; columnIndex += 1) { |
| 23 | + if (s1[columnIndex - 1] === s2[rowIndex - 1]) { |
| 24 | + lcsMatrix[rowIndex][columnIndex] = lcsMatrix[rowIndex - 1][columnIndex - 1] + 1; |
| 25 | + } else { |
| 26 | + lcsMatrix[rowIndex][columnIndex] = Math.max( |
| 27 | + lcsMatrix[rowIndex - 1][columnIndex], |
| 28 | + lcsMatrix[rowIndex][columnIndex - 1], |
| 29 | + ); |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + // Calculate LCS based on LCS matrix. |
| 35 | + if (!lcsMatrix[s2.length][s1.length]) { |
| 36 | + // If the length of largest common string is zero then return empty string. |
| 37 | + return ''; |
| 38 | + } |
| 39 | + |
| 40 | + let lcs = ''; |
| 41 | + let columnIndex = s1.length; |
| 42 | + let rowIndex = s2.length; |
| 43 | + |
| 44 | + while (columnIndex > 0 || rowIndex > 0) { |
| 45 | + if (s1[columnIndex - 1] === s2[rowIndex - 1]) { |
| 46 | + // Move by diagonal left-top. |
| 47 | + lcs = s1[columnIndex - 1] + lcs; |
| 48 | + columnIndex -= 1; |
| 49 | + rowIndex -= 1; |
| 50 | + } else if (lcsMatrix[rowIndex][columnIndex] === lcsMatrix[rowIndex][columnIndex - 1]) { |
| 51 | + // Move left. |
| 52 | + columnIndex -= 1; |
| 53 | + } else { |
| 54 | + // Move up. |
| 55 | + rowIndex -= 1; |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + return lcs; |
| 60 | +} |
0 commit comments