C # KMP algorithm string matching

Source: Internet
Author: User

Proposition: Design algorithm, in string s, starting at the POS position to find the first starting position of the same substring as the target string T.

KMP algorithm implementation: The first step is to preprocess the target string T to find out where each character in T is moved to when the character in the source string s is unequal. The method is based on the following formula

next[0]=-1;
next[j]=max{k|0<k<j&&"t0t1...t(k-1)"=="t(j-k)t(j-k+1)...t(j-1)"};
next[j]=0;

This formula can be proved as follows

First, assuming that the target string moves to K next time, what is the characteristic of this k position, all the characters before K (K, starting from 0) should be the same as the K characters before the I position in the source string s, namely:

"t0t1...t(k-1)"=="s(i-k)s(i-k+1)...s(i-1)"

Moreover, at this point, the K characters before the source string I position and the K character before the target string J position are the same, namely:

"t(j-k)t(j-k+1)...t(j-1)"=="s(i-k)s(i-k+1)...s(i-1)"

So get to the conclusion

"t0t1...t(k-1)"=="t(j-k)t(j-k+1)...t(j-1)"

The second step is to loop the source string and the target string, such as the next, this paragraph is not easy to say

while (S[i]!= ' && t[j]!= ')
{
if (j = = 1 | | s[i] = = T[j])//j==-1 indicates s[i] is different from t[0
{
i++;
j + +;
}
Else
{
j = Next[j];
}
}
if (t[j] = = ")
return i-j;
Else
return 0;

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.