Skip to content

Instantly share code, notes, and snippets.

@xpqz

xpqz/kmp.cpp Secret

Created June 25, 2021 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xpqz/461d6a1564ab4e9be69374e665fa1031 to your computer and use it in GitHub Desktop.
Save xpqz/461d6a1564ab4e9be69374e665fa1031 to your computer and use it in GitHub Desktop.
// to compile (using gcc 4.7.2):
// g++ kmp.cpp -std=c++11 -pedantic -o kmp.out
// to run:
// dos2unix <rosalind_kmp.txt | ./kmp.out > kmp.answer
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::string p;
getline(std::cin, p);
const int m = p.size();
std::vector<int> b(m+1);
// Knuth-Morris-Pratt algorithm: Preprocesing
int i = 0; int j = -1;
b[i] = j;
while (i < m) {
while (j >= 0 && p[i] != p[j]) j = b[j];
++i; ++j;
b[i] = j;
}
// `failure array' is now in b[1:m+1)
for (i=1; i<m; ++i) std::cout <<b[i] <<' ';
std::cout <<b[m];
//std::cout <<std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment