The Knuth-Morris-Pratt string searching algorithm searches for occurrences of a "pattern" string within a main string by employing the simple observation that when a mismatch occurs, we have enough knowledge simply by possessing the pattern to determine where the next match could begin, thus bypassing re-examination of previously matched characters.
#include <iostream>

int *ComputePrefixFunction(char *p)

...{
int m=strlen(p);
int *c=new int[m];
memset(c,0,m*sizeof(int));
c[0]=0;
int k=0;
for(int q=2;q<=m;q++)

...{
while(k>0&&p[k]!=p[q-1])
k=c[k-1];
if(p[k]==p[q-1])
k=k+1;
c[q-1]=k;
}

return c;
}

void KMP_Matcher(char *t,char *p)

...{
int n=strlen(t);
int m=strlen(p);
int *c=new int[m];
memset(c,0,m*sizeof(int));
c=ComputePrefixFunction(p);
int q=0;
for(int i=1;i<=n;i++)

...{
while(q>0&&p[q]!=t[i-1])
q=c[q-1];
if(p[q]==t[i-1])
q=q+1;
if(q==m)

...{
printf("Pattern occurs with shift %d ",i-m+1);
q=c[q-1];
}
}
}

int main()

...{
KMP_Matcher("dsfdsfsshefgfdgshedsfdfshe","she");
return 0;
}






















































