Skip to content

Instantly share code, notes, and snippets.

@trolley813
Created December 3, 2020 06:42
Show Gist options
  • Select an option

  • Save trolley813/b155f2597374a82fa35af0f21503984c to your computer and use it in GitHub Desktop.

Select an option

Save trolley813/b155f2597374a82fa35af0f21503984c to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<int> prefix(string str) {
int n = str.size();
vector<int> p(n);
p[0] = 0;
for (int i = 1; i < n; i++) {
int q = p[i - 1];
test:
if (str[i] == str[q]) {
p[i] = q + 1;
}
else {
if (q == 0) {
p[i] = 0;
}
else {
q = p[q - 1];
goto test;
}
}
}
return p;
}
vector<int> kmp(string pattern, string str) {
int k = 0;
vector<int> p = prefix(pattern);
vector<int> a;
int length = str.size();
for (int i = 0; i < length; i++) {
while (k > 0 && str[i] != pattern[k]) {
k = p[k - 1];
}
if (str[i] == pattern[k]) {
k++;
}
if (k == pattern.size()) {
int pos = i - k + 1;
a.push_back(pos);
k = p[k - 1];
}
}
return a;
}
int main() {
string str = "1213121214121"s;
string pat = "121"s;
vector<int> matches = kmp(pat, str);
for (int m : matches) {
cout << m << endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment