KMP pattern matching algorithm (2)

Source: Internet
Author: User

When the substring is aaaab, there will be unnecessary backtracking.


Because the next array is 01234 at this time, if the main string s [I]! = T [4], J values are traced back in sequence, but the first four are all identical characters, so tracing of J values is unnecessary.


That is to say, when the substring has repeated characters, the value in the next array corresponding to it only needs to be the same as the value recorded in the next array when it first appeared. For example, for a substring 'A', 'B ', 'A', 'B', 'A', 'C', 'A', 'c'. The improved next array should be 010104102


New next array generationCode:

Void get_nextval (char * t, int * Next) {int I, j; I = 1; j = 0; next [I] = 0; while (I <t [0]) {If (j = 0 | T [I] = T [J]) {++ I; ++ J; if (T [I]! = T [J]) {next [I] = J;} else {next [I] = next [J];} else {J = next [J] ;}}

KMP Code only needs to replace get_next (T, next); with get_nextval (T, next );


010104102

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.