Read the article from
Http://www.cnblogs.com/c-cloud/p/3224788.html
Good understanding of the method of seeking next (recommended to see the original)
Next implementation
1 voidMakenext (Const CharP[],intnext[])2 {3 intQ,k;//Q: Template string subscript; k: Maximum prefix length4 intm = strlen (P);//Template String Length5next[0] =0;//The maximum prefix length for the first character of a template string is 06 for(q =1, k =0; Q < m; ++Q)//For Loop, starting with the second character, and sequentially calculating the next value for each character7 {8 while(k >0&& p[q]! = P[k])//recursion to find out p[0] P[Q] The largest and the same prefix length k9K = next[k-1];//don't understand it's okay look at the following analysis, this while loop is the essence of the whole code, it's really not good to understandTen if(P[q] = = P[k])//if equal, then the maximum same prefix length plus 1 One { Ak++; - } -NEXT[Q] =K; the } -}
KMP implementation
1#include <stdio.h>2#include <string.h>3 voidMakenext (Const CharP[],intnext[])4 {5 intq,k;6 intm =strlen (P);7next[0] =0;8 for(q =1, k =0; Q < m; ++q)9 {Ten while(k >0&& P[q]! =P[k]) OneK = next[k-1]; A if(P[q] = =P[k]) - { -k++; the } -NEXT[Q] =K; - } - } + - intKmpConst CharT[],Const CharP[],intnext[]) + { A intn,m; at inti,q; -n =strlen (T); -m =strlen (P); - Makenext (p,next); - for(i =0, q =0; I < n; ++i) - { in while(Q >0&& P[q]! =T[i]) -Q = next[q-1]; to if(P[q] = =T[i]) + { -q++; the } * if(q = =m) $ {Panax Notoginsengprintf"Pattern occurs with shift:%d\n", (i-m+1)); - } the } + } A the intMain () + { - inti; $ intnext[ -]={0}; $ Chart[ -], p[ -]; -scanf"%s%s", t,p); - theprintf"%s\n", T); -printf"%s\n", P);Wuyi //Makenext (p,next); the KMP (t,p,next); - for(i =0; I < strlen (P); ++i) Wu { -printf"%d", Next[i]); About } $printf"\ n"); - - return 0; -}
KMP algorithm, which is the simplest and best understanding of the KMP algorithm I see