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