The second of string pattern matching algorithm: KMP algorithm

Source: Internet
Author: User

Introduction to the KMP algorithm

The full name of the KMP algorithm is called Knuth-morris-pratt algorithm.

The string being searched is called the main string, and the strings to be searched are called pattern strings.

We know the naïve pattern matching algorithm: http://blog.csdn.net/chfe007/article/details/43448655 is very inefficient, the KMP algorithm starts from the pattern string and discovers the hidden information in the pattern string to reduce the number of comparisons. Specifically how to do this can be the link: http://kb.cnblogs.com/page/176818/

The key to the KMP algorithm is the derivation of the next array value .

Next array derivation
void GetNext (char *needle,int Len,int*Next) {inti =0, j =-1;Next[0] = -1; while(I <Len-1) {if(j = =-1|| Needle[i] = = Needle[j])Next[++i] = ++j;Elsej =Next[j]; }    }
Improvement of next array derivation
void Getnextimp (char *needle,int Len,int*Next) {inti =0, j =-1;Next[0] = -1; while(I <Len-1) {if(j = =-1||                Needle[i] = = Needle[j]) {++i; ++j;Next[I] = (needle[i] = = Needle[j]?Next[j]: J); }Elsej =Next[j]; }    }
KMP Algorithm Implementation
    intStrStr (Char*haystack, Char*needle) {intHaystacklen = strlen (haystack);intNeedlelen = strlen (needle);int *next= newint[Needlelen];//GetNext (Needle, Needlelen,Next); Getnextimp (Needle, Needlelen,Next);inti =0, j =0; while(I < Haystacklen && J < Needlelen) {if(j = =-1||                Haystack[i] = = Needle[j]) {++i;            ++j; }Else{j =Next[j]; }        }returnJ >= Needlelen? I-needlelen:-1; }

Two of the string pattern matching algorithms: KMP algorithm

Contact Us

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.