Skip to content

Instantly share code, notes, and snippets.

@behitek
Forked from shihongzhi/KMP.cpp
Created November 17, 2018 02:13
Show Gist options
  • Save behitek/004af8bdc21819270718d1dc58f23322 to your computer and use it in GitHub Desktop.
Save behitek/004af8bdc21819270718d1dc58f23322 to your computer and use it in GitHub Desktop.
KMP
//shihongzhi -- 2012.3.9
#include <stdio.h>
#include <string.h>
void KMP(char *T, char *P, int *pi)
{
int tLen = strlen(T);
int pLen = strlen(P);
int k = 0;
for (int i=0; i<tLen; ++i)
{
while (k>0 && P[k] != T[i])
{
k = pi[k];
}
if (P[k] == T[i])
{
k++;
}
if (k==pLen)
{
printf("%d\n", i-pLen+1);
k = pi[k];
}
}
}
//预处理子串
void computePrefix(char *P, int *pi)
{
int k;
pi[1] = 0;
k = 0;
int len = strlen(P);
for (int i=1; i<len; ++i)
{
while (k>0 && P[k]!=P[i])
{
k = pi[k];
}
if (P[k] == P[i])
{
k++;
}
pi[i+1] = k;
}
}
int main()
{
char T[] = "bacbababaabcbaba";
char P[] = "aba";
int pi[100];
computePrefix(P, pi);
KMP(T, P, pi);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment