Goal
If P[1: q] is matched with T[s+1: s+q] but P[q+1] != T[s+q+1],
then we want to find a smallest s' > s such that with some q' < q
we have P[1: q'] matched with T[s'+1: s'+q'].


in other words
Find the longest prefix of P[1: q]
that is also a suffix of T[1: s+q], if P[1: q] is matched with T[s+1: s+q].
Prefix Function
1 | vector<int> prefix_func(string &s){ |
Complexity
- Time: O(m), m = length of pattern
Q: Why not O(m^2)?
A: for eachprev, it can only be incremented once every iteration.prevcan be decremented at mostmtimes duringmiteration of the for loop, since the increment operation happens at mostmtimes.
Matching
1 | void kmp(string &text, string &pattern){ |
Credits
- images from slides of DSA course by Prof. Michael Tsai, NTU CSIE