Principle Reference ACM Algorithm Training tutorial Book
*KMP algorithm */#include <stdio.h> #include <string.h># Include<iostream>using namespace Std;void getNext (char a[],int next[]) {int i,j;next[1] = 0;j = 0;i = 2;int m = Strle N (a)-1; Starting from a[1] while (i<=m) {if (a[j+1] = = A[i]) {j + +; next[i++] = j;} else if (j==0) {next[i++] = 0;} else if (j>0) {j = next[j];}}} int match (char A[],char b[],int next[]) {int i=0,j=0;int pos;int n = strlen (a) -1;int m = strlen (b) -1;while (1) {if (i>n) {p OS =-1; break;} if (j==m) {//pos = i-j+1; break;cout<<i-j+1<< "" <<endl; J=NEXT[J];} if (b[j+1] = = A[i+1]) {j + +; i++;} Else{if (j==0) I++;else if (j>0) {j = next[j];}}} /* int main () {//char b[] = "!ABABBC"; char b[] = "!abab"; int l = strlen (b); int *next = new Int[l-1];getnext (b,next); int i ; for (i=1;i<=l-1;i++) {printf ("%d", Next[i]);} Cout<<endl;char a[] = "!ABABABABBC"; int pos = match (a,b,next); Cout<<endl<<pos<<endl;} *////////////////////////////////////////////////////*KMP application: Find the substring length of all prefixes equal to suffix in a string */void output (int i,int next[]) {while (next[i]>0) {cout<<next[i]<< ""; Next[i];}} /*int Main () {char b[] = "!ababa"; int l = strlen (b); int *next = new Int[l-1];getnext (b,next); int i;for (i=1;i<=l-1;i++) { printf ("%d", Next[i]);} Cout<<endl;output (L-1,next);d elete[] next; */
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
KMP algorithm-C language Program implementation