“This is the 16th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
KMP
The time complexity of -KMP algorithm is O(m+ N), and the main advantage is that the main string does not backtrace
I. Example diagram
# 2
Analyze the above example
P as mode string 'aabaac's 'as main string' aabaabaac'Copy the code
1. First we solve the next array
2. The main string goes straight ahead, and the mode string is compared
A a b a a b a b a a c a a b a a a a a b a a 'c' Next [6]= next[j]' ② a a b a a b a b a c a a b a a b a a'c' A a b a a B a a B a a C a a b a A A C a A B a A CCopy the code
Method two in the example above
Case 1 figure
1. First of all, we first work out partial matching values of the prefixes and suffixes of the pattern string, such as' Fig.1 '2. A a B A B a B A A B A A C a A B A A A A B a A 'C' So we see that the fifth digit 'a' matches '2', and the matched digit is '5', so using the formula '5-2=3', we move the pattern string back three places to get ② ② A A B A B A B A A C A B A A 'C' again, same idea, Again, '5-2=3'. Move the pattern string back three places to get ③ ③ a A B a B a A B A A C a B a A A CCopy the code
eggs
- At this point, let’s go back to example 1, where we want to figure out
next
The array is the one shown in figure 1 - Match the value
It goes one to the right
Isn’t it amazing!