String algorithm-KMP Algorithm

Source: Internet
Author: User

The KMP algorithm is a major improvement to the string matching algorithm. It uses the characteristics of the substring to improve the algorithm efficiency.


The key or essence of the KMP algorithm is the computation with next.


Assume that the primary string S and the sub-string T exist. In a match, we find T (k )! = S (I + 1)


Then we get a matching result.

That is: T (1) ...... T (k-1) = S (I-k + 1) ...... S (I-1)


Let's assume that there is a j <k making: T (1 )...... T (J-1) = S (I-k + 1 )..... S (I-k + J-1)

That is to say T (1) ...... T (J-1) = T (k-j) ...... T (k-1)

Therefore, we need to move the substring to the right k-j bit. If this is not the case, that is, j = 0, then we need to move the k-bit to the right.

Therefore, we only need to find the j corresponding to each position in the substring.

This is the idea of the KMP algorithm.


Therefore, the next () function is defined as follows:


0 j = 1

Next () = max (k/1 <= k

1 If the above K does not exist and T (1 )! = T (j)

0 if the above K does not exist and T (1 )! = T (I)



The code for finding the next () function is as follows:

Char s [100]; // The matched string char t [100]; // The matched string int next [100]; // store the int s_length, t_length, and the distance between each character in the matching string. // The length of the character void getnext () {int I = 0, j =-1; next [I] =-1; while (I <t_length) {while (j> = 0 & t [I]! = T [j]) j = next [j]; // compare it with the character before the character to see if it is the same as the character before I ++; j ++; if (t [I] = t [j]) next [I] = next [j]; // if the current two characters are the same, else next [I] = j ;} for (I = 0; I <t_length; I ++) printf ("% d \ n", next [I]) ;}// the sliding distance to the right is: j-next [j]






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.