This paper is aimed at the data structure Basic Series Network course (4): The pattern match (KMP algorithm) of the 5th lesson string.
Problem: pattern matching for strings
KMP algorithm:
#include <stdio.h>#include "sqString.h"void GetNext (Sqstring t,int Next[]) /* byPattern string T to find outNextValue*/{intJ,k; j=0; k=-1;Next[0]=-1; while(J<t.length-1) {if(k==-1|| T.DATA[J]==T.DATA[K])/*kFor1Or comparison of words typeface etc.*/{j + +; k++;Next[J]=k; }Elsek=Next[K]; }}intKmpindex (sqstrings, sqstring t)/*KMPAlgorithm*/{int Next[maxsize],i=0, j=0; GetNext (T,Next); while(i<s.length&& j<t.length) {if(j==-1||s. Data[i]==t.data[j]) {i++; j + +;/*i,j each increase 1*/}Elsej=Next[j];/*i the same, J back * /}if(J>=t.length)return(I-t.length);/ * Returns the first word of the matching pattern string Poute * / Else return(-1);/ * Returns a mismatch flag * /}intMain () {sqstrings, t; Strassign (s,"Ababcabcacbab"); Strassign (T,"ABCAC");printf("s:"); DISPSTR (s);printf("T:"); DISPSTR (t);printf("Location:%d\ n", Kmpindex (s, t));return 0;}
The Modified KMP algorithm
#include <stdio.h>#include "sqString.h"void Getnextval (Sqstring t,intNextval[])//By the pattern string T to find the Nextval value {intj=0, k=-1; nextval[0]=-1; while(J<t.length) {if(k==-1|| T.data[j]==t.data[k]) {j + +; k++;if(T.data[j]!=t.data[k]) nextval[j]=k;ElseNEXTVAL[J]=NEXTVAL[K]; }ElseK=NEXTVAL[K]; }}intKMPIndex1 (sqstrings, sqstring t)//modified KMP algorithm {intNextval[maxsize],i=0, j=0; Getnextval (T,nextval); while(i<s.length&& j<t.length) {if(j==-1||s. Data[i]==t.data[j]) {i++; j + +; }ElseJ=NEXTVAL[J]; }if(J>=t.length)return(I-t.length);Else return(-1);}intMain () {sqstrings, t; Strassign (s,"Ababcabcacbab"); Strassign (T,"ABCAC");printf("s:"); DISPSTR (s);printf("T:"); DISPSTR (t);printf("Location:%d\ n", KMPIndex1 (s, t));return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Data structure Routines--string pattern matching (KMP algorithm)