# Data structure Routines--string pattern matching (KMP algorithm)

Source: Internet
Author: User

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;}``

Data structure Routines--string pattern matching (KMP algorithm)

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.