Skip to content

Instantly share code, notes, and snippets.

@krofna
Created March 11, 2019 14:52
Show Gist options
  • Save krofna/f6f79ea02978f498f83413b300c0cf5f to your computer and use it in GitHub Desktop.
Save krofna/f6f79ea02978f498f83413b300c0cf5f to your computer and use it in GitHub Desktop.
void init(string& P, vi& b)
{
int i = 0, j = -1; b[0] = -1;
while (i < P.size())
{
while (j >= 0 && P[i] != P[j]) j = b[j];
b[++i] = ++j;
}
}
vi kmp(string& T, string& P, vi& b)
{
vi ret;
int i = 0, j = 0;
while (i < T.size())
{
while (j >= 0 && T[i] != P[j]) j = b[j];
++i; ++j;
if (j == P.size())
{
ret.push_back(i - j);
j = b[j];
}
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment