forked from NKaty/Algorithms-and-Data-Structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathknuth-morris-pratt-search.js
82 lines (70 loc) · 2.05 KB
/
knuth-morris-pratt-search.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Knuth-Morris-Pratt algorithm
// Write a function which accepts a string and a pattern, and returns the index
// at which the value exists. If the pattern does not exist in the string, return -1.
// Time Complexity - O(n + m)
// Space complexity - O(n)
function buildArrayPattern(pattern) {
const arrayPattern = [0];
let prefix = 0;
let suffix = 1;
while (arrayPattern.length < pattern.length) {
if (pattern[prefix] === pattern[suffix]) {
arrayPattern.push(prefix + 1);
prefix++;
suffix++;
} else if (prefix === 0) {
arrayPattern.push(0);
suffix++;
} else {
prefix = arrayPattern[prefix - 1];
}
}
return arrayPattern;
}
function kmp(text, pattern) {
const arrayPattern = buildArrayPattern(pattern);
let textIndex = 0;
let patternIndex = 0;
while (textIndex < text.length) {
if (text[textIndex] === pattern[patternIndex]) {
if (patternIndex === pattern.length - 1) {
return textIndex - pattern.length + 1;
} else {
textIndex++;
patternIndex++;
}
} else if (patternIndex === 0) {
textIndex++;
} else {
patternIndex = arrayPattern[patternIndex - 1];
}
}
return -1;
}
console.log(kmp('dabcdabcyabkglabcdcxabcdabcdabcy', 'abcdabcy')); // 1
console.log(kmp('dabcdabcyabkglabcdcxabcdabcdabcy', 'abcdabcyd')); // -1
function kmpCounter(text, pattern) {
const arrayPattern = buildArrayPattern(pattern);
let textIndex = 0;
let patternIndex = 0;
let counter = 0;
while (textIndex < text.length) {
if (text[textIndex] === pattern[patternIndex]) {
if (patternIndex === pattern.length - 1) {
textIndex++;
patternIndex = 0;
counter++;
} else {
textIndex++;
patternIndex++;
}
} else if (patternIndex === 0) {
textIndex++;
} else {
patternIndex = arrayPattern[patternIndex - 1];
}
}
return counter;
}
console.log(kmpCounter('dabcdabcyabkglabcdcxabcdabcdabcy', 'abcdabcy')); // 2
console.log(kmpCounter('dabcdabcyabkglabcdcxabcdabcdabcy', 'abcdabcyd')); // 0