/
22_longest_common_substring.js
executable file
·58 lines (44 loc) · 1.18 KB
/
22_longest_common_substring.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
Given two strings, write a function that returns the longest common substring.
eg.
substring ("ABAB", "BABA") = "ABA"
"ABAB"
^
"BABA"
^
A B A B
B [0, 1, 0, 1]
A [1, 0, 2, 0]
B [0, 2, 0, 3]
A [1, 0, 3, 0]
*/
function longestCommonSubstring(str1, str2) {
let result = '';
if (str1.length === 0 || str2.length === 0) return result;
let cache = [];
let longest = 0;
for (let i = 0; i < str1.length; i++) {
let row = [];
for (let j = 0; j < str2.length; j++) {
if (str1[i] === str2[j]) {
if (i !== 0 && j !== 0) {
let currentLength = cache[i - 1][j - 1] + 1;
row.push(currentLength);
if (currentLength > longest) {
longest = currentLength;
result = str1.substring(i - longest + 1, i + 1);
}
} else {
row.push(1);
}
}
else {
row.push(0);
}
}
cache.push(row);
}
//for (let row of cache) console.log(row);
return result;
}
longestCommonSubstring("ABAB", "BABA");