An understanding of the KMP algorithm (vi)

Source: Internet
Author: User

In front of the KMP algorithm to do a variety of explanations, now the algorithm to do a code implementation:

intKmpsearch (Char*s,Char*p) {    inti =0; intj =0; intSlen =strlen (s); intPlen =strlen (P);  while(I < Slen && J <Plen) {        //If J =-1, or if the current character matches successfully (that is, s[i] = = P[j]), make i++,j++        if(j = =-1|| S[i] = =P[j]) {i++; J++; }        Else        {            //if J! =-1, and the current character match fails (that is, s[i]! = P[j]), then I is unchanged, j = Next[j]//Next[j] is the next value corresponding to Jj =Next[j]; }    }// while    if(J = =Plen) {        returnIJ; }    Else    {        return-1; }}

Time complexity analysis of KMP algorithm:

If the length of the text string is n and the length of the pattern string is M, then the time complexity of the matching process is O (n), which calculates the O (m) time of next, and the overall time complexity of the KMP is O (M + N).

An understanding of the KMP algorithm (vi)

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: 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.