KMP algorithm string Matching

Source: Internet
Author: User

For brute force search, when the character corresponding to the search term does not match the character in the string. Move the search term one after the other, and then compare it from the beginning. While this works, it is inefficient, because you want to move the "search location" to a location that has been compared again.

After applying the KMP algorithm, there are:
MoveMovingbitnumber=have beenHorsewithof theWordcharacternumber?theshould beof theDepartmentpointsHorsewithvalue

The partial match value is the length of the longest common element of the prefix and suffix.

The KMP algorithm implements the code as follows :

voidPrefixfun (Char*pattern,int*prefun) {intLen =0;//length of Pattern     while(' + '! = Pattern[len]) len++;intLolp =0;//length of longest prefixprefun[1] =0; for(intNOCM =2; NOCM <= Len; nocm++)//nocm:number of characters matched{ while(Lolp >0&& Pattern[lolp]! = pattern[nocm-1]) Lolp = Prefun[lolp];if(Pattern[lolp] = = pattern[nocm-1]) lolp++;    PREFUN[NOCM] = Lolp; }}voidKmpstrmatching (Char*target,Char*pattern) {intTarlen =0;intPatlen =0; while(' + '! = Target[tarlen]) tarlen++; while(' + '! = Pattern[patlen]) patlen++;int*prefun =New int[patlen+1]; Prefixfun (pattern, prefun);intNOCM =0;//number of characters matched     for(inti =0; i < Tarlen; i++) { while(Nocm >0&& PATTERN[NOCM]! = target[i]) nocm = prefun[nocm];if(PATTERN[NOCM] = = Target[i]) nocm++;if(nocm = = Patlen) {cout<<"Pattern occurs with Shift"<<i-patlen +1<<endl;        NOCM = prefun[nocm]; }    }Delete[] prefun;}

KMP algorithm string Matching

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.