KMP Algorithm Summary

Source: Internet
Author: User

There must be a lot of people on the KMP algorithm, learned many times, or do not understand, in fact, very simple, we simply look at two problems, you can!

General violence algorithm, everyone, should know, sweep two times, direct comparison, you can get the answer,

We see directly, there is no simplification

First, the same as the general algorithm, directly match, until P[i]!=p[j]; At this time, if the general algorithm I want to back back, J also to start again, but we did not make good use of the useful information has been obtained


Already know, the preceding paragraph is equal, we can think of a way, do not let I move, direct comparison, this is some, if we know, J Front string, the maximum prefix equals suffix, is the mark A is equal,

Then, do not move I, directly compare p[i]==p[next[j]], you can!

In this way, the next array is introduced, the next array, simple point, is the maximum prefix equals suffix, is required to the maximum length of a, you can!

So how to find the maximum length of a, look at this figure

If p[i-1] = = P[k], then we can directly get next[i]= next [i-1]+1;

If, not equal, we can use a recursive derivation,


, we know, p[i-1]! = P[k]; But we also know useful information A0 A1 A2 is the same string!

At this point, we put k = Next[k], then, according to the definition of the next array, we know that B0 B1 B2 B3 B4 B5 are the same, then, we just compare p[i-1] = = P[next[k]], can be obtained next[i-1], of course, if not equal, Then k = next [K], so that, to be sure, find the beginning of the end of the point, you can get the answer!

I learn KMP is also do not understand why, so always forget, since the drawing of these two pictures, no longer have to recite the code, you can write it out, so I hope readers, understand the two map, naturally understand the KMP algorithm!

KMP Algorithm Summary

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.