KMP algorithm and next array solver

Source: Internet
Author: User

These days toss the next KMP, finally understood the principle. Now here is probably recorded, in case of a rainy days!!

  

Char STR[MAXN];    // Original String     Char P[MAXN];    // string to look for in the original string

In contrast to the general string matching, the KMP algorithm is optimized where the current matching position K + 1 match fails, not to go back to the start of P to match, but back to Next[k] to start matching!

Next[k] in P[0...K], the longest of the same prefix suffix length-1,-1 is convenient for the time of transfer (array starting from 0).

Like what:

For

/* p:| A | b | a | a | b | c | a | c |next:| -1| -1| 0 | 0 | 1 | -1| 0 | -1| */

The same prefix suffix is the same prefix and suffix;

The next array is then the method of seeking:

Here is a copy of the code in the introduction of the algorithm, very ingenious, if you do not know the principle of simulation is clear.

voidGet_next (Char*p,int*next) {next[0] = -1; intK =-1;  for(inti =1; i < p.length; i++){         while(K >-1&& P[k +1] !=P[i]) k=Next[k]; if(P[k +1] ==P[i]) {k++; } Next[i]=K; }}

With the next array, when you find a mismatch in the matching string program, you do not need to reset the position of P to 0 and assign it to next[k].

This article is just a simple description of the next KMP for forgetting, more detailed analysis of the online gods can see the blog

http://blog.csdn.net/v_july_v/article/details/7041827

KMP algorithm and next array solver

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.