2018/2/21 Daily One Learning KMP algorithm

Source: Internet
Author: User

KMP algorithm

What is the KMP algorithm?

Ask a question first: Given the string A and B, satisfy B must be a substring, ask first B and a overlapping b[1] corresponding to the ordinal of a.

As an example: a:ababcedabced,b:abced

So the answer is obviously 3, that is, a[3] starts the first time with B.

So it's easy to think of the Brute Force algorithm O (n*m), right?

Obviously easy tle ...

Here we introduce a simple string matching algorithm: KMP.

An example: A:ABABC,B:ABC;

I=1,j=1, A[i]=b[j], continue, i++,j++,a[i]=b[j], continue, i++, but this is a[i]!=b[j+1],j can't + +,

What to do?

We can migrate the B array as a whole (note the correspondence, as below)

A:ababc

B:abc

This is j=1,i=3,a[i]=b[j], continue ...

Then we are not hard to get the main function:

j=0;  for (int =1; i<=n;i++) {while (j>0&&b[j+1 ]!=a[i]) j=p[j]; if (b[j+1]=a[i]) j + +; if (j==m) ans=i-m;}

So how does the P array, that is, how to shift the B array?
Much like the main function:

p[1]=0; J=0;  for (int i=2; i<=m;i++) {while (j>0&&b[j+1]!=b [i]) j=P[j]; if (b[j+1]==b[i]) j + +;p [i]=j;}

Have you learned it?

2018/2/21 Daily One Learning KMP algorithm

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.