forked from loiane/javascript-datastructures-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathknuth-morris-pratt.ts
46 lines (40 loc) · 896 Bytes
/
knuth-morris-pratt.ts
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
const buildTable = (pattern: string) => {
const length = pattern.length;
const table = [];
let position = 2;
let cnd = 0;
table[0] = -1;
table[1] = 0;
while (position < length) {
if (pattern[position - 1] === pattern[cnd]) {
table[position++] = ++cnd;
} else if (cnd > 0) {
cnd = table[cnd];
} else {
table[position++] = 0;
}
}
return table;
};
const knuthMorrisPratt = (text: string, pattern: string) => {
const textLength = text.length;
const patternLength = pattern.length;
let m = 0;
let i = 0;
const table = buildTable(pattern);
while (m + i < textLength) {
if (pattern[i] === text[m + i]) {
if (i === patternLength - 1) {
return m;
}
i++;
} else if (table[i] >= 0) {
i = table[i];
m = m + i - table[i];
} else {
i = 0;
m++;
}
}
return textLength;
};