|
1 | 1 | /** |
2 | | - * @param {string} s1 |
3 | | - * @param {string} s2 |
| 2 | + * @param {string} string1 |
| 3 | + * @param {string} string2 |
4 | 4 | * @return {string} |
5 | 5 | */ |
6 | | -export default function longestCommonSubstring(s1, s2) { |
7 | | - // transform s1 & s2 into arrays to allow handling unicodes as single caracter. |
8 | | - const [a1, a2] = [s1, s2].map(s => Array.from(s)); |
| 6 | +export default function longestCommonSubstring(string1, string2) { |
| 7 | + // Convert strings to arrays to treat unicode symbols length correctly. |
| 8 | + // For example: |
| 9 | + // '𐌵'.length === 2 |
| 10 | + // [...'𐌵'].length === 1 |
| 11 | + const s1 = [...string1]; |
| 12 | + const s2 = [...string2]; |
9 | 13 |
|
10 | 14 | // Init the matrix of all substring lengths to use Dynamic Programming approach. |
11 | | - const substringMatrix = Array(a2.length + 1).fill(null).map(() => { |
12 | | - return Array(a1.length + 1).fill(null); |
| 15 | + const substringMatrix = Array(s2.length + 1).fill(null).map(() => { |
| 16 | + return Array(s1.length + 1).fill(null); |
13 | 17 | }); |
14 | 18 |
|
15 | 19 | // Fill the first row and first column with zeros to provide initial values. |
16 | | - for (let columnIndex = 0; columnIndex <= a1.length; columnIndex += 1) { |
| 20 | + for (let columnIndex = 0; columnIndex <= s1.length; columnIndex += 1) { |
17 | 21 | substringMatrix[0][columnIndex] = 0; |
18 | 22 | } |
19 | 23 |
|
20 | | - for (let rowIndex = 0; rowIndex <= a2.length; rowIndex += 1) { |
| 24 | + for (let rowIndex = 0; rowIndex <= s2.length; rowIndex += 1) { |
21 | 25 | substringMatrix[rowIndex][0] = 0; |
22 | 26 | } |
23 | 27 |
|
@@ -26,9 +30,9 @@ export default function longestCommonSubstring(s1, s2) { |
26 | 30 | let longestSubstringColumn = 0; |
27 | 31 | let longestSubstringRow = 0; |
28 | 32 |
|
29 | | - for (let rowIndex = 1; rowIndex <= a2.length; rowIndex += 1) { |
30 | | - for (let columnIndex = 1; columnIndex <= a1.length; columnIndex += 1) { |
31 | | - if (a1[columnIndex - 1] === a2[rowIndex - 1]) { |
| 33 | + for (let rowIndex = 1; rowIndex <= s2.length; rowIndex += 1) { |
| 34 | + for (let columnIndex = 1; columnIndex <= s1.length; columnIndex += 1) { |
| 35 | + if (s1[columnIndex - 1] === s2[rowIndex - 1]) { |
32 | 36 | substringMatrix[rowIndex][columnIndex] = substringMatrix[rowIndex - 1][columnIndex - 1] + 1; |
33 | 37 | } else { |
34 | 38 | substringMatrix[rowIndex][columnIndex] = 0; |
@@ -53,7 +57,7 @@ export default function longestCommonSubstring(s1, s2) { |
53 | 57 | let longestSubstring = ''; |
54 | 58 |
|
55 | 59 | while (substringMatrix[longestSubstringRow][longestSubstringColumn] > 0) { |
56 | | - longestSubstring = a1[longestSubstringColumn - 1] + longestSubstring; |
| 60 | + longestSubstring = s1[longestSubstringColumn - 1] + longestSubstring; |
57 | 61 | longestSubstringRow -= 1; |
58 | 62 | longestSubstringColumn -= 1; |
59 | 63 | } |
|