Learn a look at the pornography algorithm I think I can get better.
Obviously yesterday's question I all know how to imitate, but still will not change KMP, is I learn ugly
KMP is a linear time string matching algorithm designed by Knuth-morris-pratt three people
An introduction to the NXT array, horizontal slot, direct find too cool
Is that I can fall back when I match, because of the limited ability of the character
For example, Aaaaaaaaab and Aaaab to match, Aaaab is a pattern string, Aaaaaaaaab is a matching string, I do not have to back so many times, because in time to push down on the good
I'm a part of the match and I can go back to a certain position.
Here is a demo
I used to ask for the prefix function
void Pre (char *p) { int i,m,j; M=strlen (p); nex[0]=nex[1]=0; for (int i=1; i<m; i++) { J=nex[i]; while (J&&p[i]!=p[j]) j=nex[j]; Nex[i+1]=p[i]==p[j]?j+1:0; }}
Aaaab
0 0 1) 2 3
Aba
0 0 0
Pseudo code
Kmp-matcher (T,P) 1N ←length[T] 2m ←length[P] 3Pi←compute-prefix-function (P) 4Q ←0? Number of characters matched. 5 for I ←1 to N ? Scan the text from left to right. 6 Do While Q > 0 andP[Q+ 1]≠T[I] 7 Do Q ←π[q ] if p [q + 1] = t [i ] 9 then q ←q + 1 if q = m p matched?11 then print "Pattern occurs with Shift" i -m q ←π[q ]
Compute-prefix-function (P) 1m ←length[P] 2Π[1]←0 3k ←0 4 for Q ←2 to m 5 do whi Le k > 0 and p [k + 1] ≠p [q ] 6 do k ←π[k ] 7 if p [k + 1] = EM class= "emphasis" >p [q ] 8 then K ←k + 1 9 π[q ] ←k return π
Getting started with the KMP algorithm