|
| 1 | +/** |
| 2 | + * @param {string} s1 |
| 3 | + * @param {string} s2 |
| 4 | + * @return {string} |
| 5 | + */ |
| 6 | +export default function longestCommonSubstring(s1, s2) { |
| 7 | + // Init the matrix of all substring lengths to use Dynamic Programming approach. |
| 8 | + const substringMatrix = Array(s2.length + 1).fill(null).map(() => { |
| 9 | + return Array(s1.length + 1).fill(null); |
| 10 | + }); |
| 11 | + |
| 12 | + // Fill the first row and first column with zeros to provide initial values. |
| 13 | + for (let columnIndex = 0; columnIndex <= s1.length; columnIndex += 1) { |
| 14 | + substringMatrix[0][columnIndex] = 0; |
| 15 | + } |
| 16 | + |
| 17 | + for (let rowIndex = 0; rowIndex <= s2.length; rowIndex += 1) { |
| 18 | + substringMatrix[rowIndex][0] = 0; |
| 19 | + } |
| 20 | + |
| 21 | + // Build the matrix of all substring lengths to use Dynamic Programming approach. |
| 22 | + let longestSubstringLength = 0; |
| 23 | + let longestSubstringColumn = 0; |
| 24 | + let longestSubstringRow = 0; |
| 25 | + |
| 26 | + for (let rowIndex = 1; rowIndex <= s2.length; rowIndex += 1) { |
| 27 | + for (let columnIndex = 1; columnIndex <= s1.length; columnIndex += 1) { |
| 28 | + if (s1[columnIndex - 1] === s2[rowIndex - 1]) { |
| 29 | + substringMatrix[rowIndex][columnIndex] = substringMatrix[rowIndex - 1][columnIndex - 1] + 1; |
| 30 | + } else { |
| 31 | + substringMatrix[rowIndex][columnIndex] = 0; |
| 32 | + } |
| 33 | + |
| 34 | + // Try to find the biggest length of all common substring lengths |
| 35 | + // and to memorize its last character position (indices) |
| 36 | + if (substringMatrix[rowIndex][columnIndex] > longestSubstringLength) { |
| 37 | + longestSubstringLength = substringMatrix[rowIndex][columnIndex]; |
| 38 | + longestSubstringColumn = columnIndex; |
| 39 | + longestSubstringRow = rowIndex; |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + if (longestSubstringLength === 0) { |
| 45 | + // Longest common substring has not been found. |
| 46 | + return ''; |
| 47 | + } |
| 48 | + |
| 49 | + // Detect the longest substring from the matrix. |
| 50 | + let longestSubstring = ''; |
| 51 | + |
| 52 | + while (substringMatrix[longestSubstringRow][longestSubstringColumn] > 0) { |
| 53 | + longestSubstring = s1[longestSubstringColumn - 1] + longestSubstring; |
| 54 | + longestSubstringRow -= 1; |
| 55 | + longestSubstringColumn -= 1; |
| 56 | + } |
| 57 | + |
| 58 | + return longestSubstring; |
| 59 | +} |
0 commit comments