-
Notifications
You must be signed in to change notification settings - Fork 0
/
knuth-morris-pratt.js
55 lines (49 loc) · 1.2 KB
/
knuth-morris-pratt.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
function computeLPSArray(pattern) {
const lps = [0];
let len = 0;
let i = 1;
while (i < pattern.length) {
if (pattern[i] === pattern[len]) {
len++;
lps[i] = len;
i++;
} else {
if (len !== 0) {
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}
return lps;
}
function KMPSearch(text, pattern) {
const n = text.length;
const m = pattern.length;
const lps = computeLPSArray(pattern);
const matches = [];
let i = 0; // index for text[]
let j = 0; // index for pattern[]
while (i < n) {
if (pattern[j] === text[i]) {
i++;
j++;
}
if (j === m) {
matches.push(i - j);
j = lps[j - 1];
} else if (i < n && pattern[j] !== text[i]) {
if (j !== 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
return matches;
}
const text = "ABABDABACDABABCABAB";
const pattern = "ABABCABAB";
const matches = KMPSearch(text, pattern);
console.log("Pattern", pattern, "found at indices:", matches);