4
4
* @return {string }
5
5
*/
6
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 ) ) ;
9
+
7
10
// 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 ) ;
11
+ const substringMatrix = Array ( a2 . length + 1 ) . fill ( null ) . map ( ( ) => {
12
+ return Array ( a1 . length + 1 ) . fill ( null ) ;
10
13
} ) ;
11
14
12
15
// Fill the first row and first column with zeros to provide initial values.
13
- for ( let columnIndex = 0 ; columnIndex <= s1 . length ; columnIndex += 1 ) {
16
+ for ( let columnIndex = 0 ; columnIndex <= a1 . length ; columnIndex += 1 ) {
14
17
substringMatrix [ 0 ] [ columnIndex ] = 0 ;
15
18
}
16
19
17
- for ( let rowIndex = 0 ; rowIndex <= s2 . length ; rowIndex += 1 ) {
20
+ for ( let rowIndex = 0 ; rowIndex <= a2 . length ; rowIndex += 1 ) {
18
21
substringMatrix [ rowIndex ] [ 0 ] = 0 ;
19
22
}
20
23
@@ -23,9 +26,9 @@ export default function longestCommonSubstring(s1, s2) {
23
26
let longestSubstringColumn = 0 ;
24
27
let longestSubstringRow = 0 ;
25
28
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
+ 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 ] ) {
29
32
substringMatrix [ rowIndex ] [ columnIndex ] = substringMatrix [ rowIndex - 1 ] [ columnIndex - 1 ] + 1 ;
30
33
} else {
31
34
substringMatrix [ rowIndex ] [ columnIndex ] = 0 ;
@@ -50,7 +53,7 @@ export default function longestCommonSubstring(s1, s2) {
50
53
let longestSubstring = '' ;
51
54
52
55
while ( substringMatrix [ longestSubstringRow ] [ longestSubstringColumn ] > 0 ) {
53
- longestSubstring = s1 [ longestSubstringColumn - 1 ] + longestSubstring ;
56
+ longestSubstring = a1 [ longestSubstringColumn - 1 ] + longestSubstring ;
54
57
longestSubstringRow -= 1 ;
55
58
longestSubstringColumn -= 1 ;
56
59
}
0 commit comments