templates/kmp.cpp
compilable
$cat templates/kmp
KMP Algorithm
Knuth-Morris-Pratt pattern matching and prefix function in O(n + m).
#kmp#pattern-matching#prefix-function#string
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <bits/stdc++.h>
using namespace std;
vector<int> prefixFunction(const string &s) {
int n = s.size();
vector<int> pi(n);
for (int i = 1; i < n; i++) {
int j = pi[i - 1];
while (j > 0 && s[i] != s[j])
j = pi[j - 1];
if (s[i] == s[j]) j++;
pi[i] = j;
}
return pi;
}
vector<int> kmpSearch(const string &text, const string &pat) {
string t = pat + "#" + text;
vector<int> pi = prefixFunction(t);
vector<int> matches;
int m = pat.size();
for (int i = m + 1; i < (int)t.size(); i++)
if (pi[i] == m)
matches.push_back(i - 2 * m);
return matches;
}26 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)
KMP Algorithm
Linear-time pattern matching using the prefix function to avoid redundant comparisons.
Prefix Function
For each position , is the length of the longest proper prefix of that is also a suffix:
Built in by maintaining and falling back via on mismatch.