/** * NAME:KMP * time:2012-11-22 * String Quick Match */#include <stdio.h> #include <string.h>typedef struct seqstring{ char string[100];int length;} Seqstring;void GetNext (seqstring p,int next[]) {int i,j;next[0]=-1;//next[0] put -1i=0;//pointer to each character of the string J=-1;while (i< P.length) {//does not reach the end if (j==-1| | P.STRING[I]==P.STRING[J]) {//If it is the first character or encounters the same character i++;j++;next[i]=j;} ELSEJ=NEXT[J];} for (i=0;i<p.length;i++) {//output next[] value printf ("%d", Next[i]);}} int KMP (seqstring t,seqstring p,int next[]) {int I,j;i=j=0;while (i<t.length&&j<p.length) {if (j==-1| | T.string[i]==p.string[j]) {i++;j++;} ELSEJ=NEXT[J];} if (j==p.length) return i-p.length;else return-1;} int main () {seqstring t,p;int next[50];p rintf ("Please input string T:"), scanf ("%s", t.string); T.length=strlen (t.string );p rintf ("Please input string P:"); scanf ("%s", p.string);p. Length=strlen (p.string); GetNext (P,next);p rintf ("\n%d\n" , KMP (T,p,next));}
KMP algorithm Template C