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