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