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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
use std::borrow::Borrow;
use std::iter::{repeat, Enumerate};
use crate::utils::TextSlice;
type LPS = Vec<usize>;
pub struct KMP<'a> {
m: usize,
lps: LPS,
pattern: TextSlice<'a>,
}
impl<'a> KMP<'a> {
pub fn new(pattern: TextSlice<'a>) -> Self {
let m = pattern.len();
let lps = lps(pattern);
KMP { lps, m, pattern }
}
fn delta(&self, mut q: usize, a: u8) -> usize {
while q == self.m || (self.pattern[q] != a && q > 0) {
q = self.lps[q - 1];
}
if self.pattern[q] == a {
q += 1;
}
q
}
pub fn find_all<'b, C, T>(&'b self, text: T) -> Matches<'b, C, T::IntoIter>
where
C: Borrow<u8>,
T: IntoIterator<Item = C>,
{
Matches {
kmp: self,
q: 0,
text: text.into_iter().enumerate(),
}
}
}
fn lps(pattern: &[u8]) -> LPS {
let (m, mut q) = (pattern.len(), 0);
let mut lps: LPS = repeat(0).take(m).collect();
for i in 1..m {
while q > 0 && pattern[q] != pattern[i] {
q = lps[q - 1];
}
if pattern[q] == pattern[i] {
q += 1;
}
lps[i] = q;
}
lps
}
pub struct Matches<'a, C, T>
where
C: Borrow<u8>,
T: Iterator<Item = C>,
{
kmp: &'a KMP<'a>,
q: usize,
text: Enumerate<T>,
}
impl<'a, C, T> Iterator for Matches<'a, C, T>
where
C: Borrow<u8>,
T: Iterator<Item = C>,
{
type Item = usize;
fn next(&mut self) -> Option<usize> {
for (i, c) in self.text.by_ref() {
self.q = self.kmp.delta(self.q, *c.borrow());
if self.q == self.kmp.m {
return Some(1 + i - self.kmp.m);
}
}
None
}
}
#[cfg(test)]
mod tests {
use super::{lps, KMP};
use itertools::Itertools;
#[test]
fn test_find_all() {
let text = b"dhjalkjwqnnnannanaflkjdklfj";
let pattern = b"qnnnannan";
let kmp = KMP::new(pattern);
assert_eq!(kmp.find_all(text).collect_vec(), [8]);
}
#[test]
fn test_find_all_at_start() {
let text = b"dhjalkjwqnnnannanaflkjdklfj";
let pattern = b"dhjalk";
let kmp = KMP::new(pattern);
assert_eq!(kmp.find_all(text).collect_vec(), [0]);
}
#[test]
fn test_lps() {
let pattern = b"ababaca";
let lps = lps(pattern);
assert_eq!(lps, [0, 0, 1, 2, 3, 0, 1]);
}
#[test]
fn test_delta() {
let pattern = b"abbab";
let kmp = KMP::new(pattern);
assert_eq!(kmp.delta(0, b'a'), 1);
assert_eq!(kmp.delta(0, b'b'), 0);
assert_eq!(kmp.delta(1, b'a'), 1);
assert_eq!(kmp.delta(1, b'b'), 2);
assert_eq!(kmp.delta(2, b'a'), 1);
assert_eq!(kmp.delta(2, b'b'), 3);
assert_eq!(kmp.delta(3, b'a'), 4);
assert_eq!(kmp.delta(3, b'b'), 0);
assert_eq!(kmp.delta(4, b'a'), 1);
assert_eq!(kmp.delta(4, b'b'), 5);
assert_eq!(kmp.delta(5, b'a'), 1);
assert_eq!(kmp.delta(5, b'b'), 3);
}
}