When it comes to string matching algorithms, it is estimated that everyone immediately thought of the KMP algorithm, who let KMP so classic, all kinds of arithmetic textbooks must have KMP ah. But the KMP algorithm is too complex for next to crash into cry. There is no simpler and more efficient algorithm than KMP, no, some, this is the Sunday algorithm to be said in this paper. KMP algorithm is a 70后, Sunday algorithm is authentic, haha.
The main reason for the slowness of the algorithm is that there are too many repetitive operations, such as brute-force search for substrings.
And the Sunday algorithm uses a very clever method, as far as possible to skip more impossible to match the position.
First, not the principle, directly from the example to see:
Text string s as follows
The pattern string T is as follows
The position of T is expected to be found from S.
A cursor I pointing to the text string s, and a cursor J pointing to the pattern string T. Initial i = 0, j = 0
1:i = 0, j= 0
S[i]! = T[j], so you need to move right I then re-match the beginning of T, then how many characters do we move?
Now let's open the hole, from the next position where S and T are aligned at the end of the current position, which is the current s[3] position, s[3] = E.
Starts to move T to the right.
----> Move one character, s[3] and t[2] to align,
Obviously this position is unlikely to match successfully because s[3]! = t[2].
----> Move two characters, s[3] and t[1] align.
Similarly, it is impossible to match success.
----> Move three characters, s[3] and t[0] align.
Similarly, it is impossible to match success.
is not a little bit of feeling, good, now to a slightly summed up the idea.
When the position I (s of the cursor), J (t's cursor) does not match, locate the next position after the POS character C, and then place the last occurrence of the character C in T, align with the POS position of S, and then re-start the validation match so that it is possible to match. If the character C does not exist in T, none of the positions of T can match the POS position of S, then only start with the position of S pos+1 and T[0].
Now, in this way, to demonstrate it again.
First step: i = 0, j = 0
The position of I and J does not match, find the next position after snapping pos = 3, the character is E, because the character e does not exist in T, all settings i = 4 (pos next position), J = 0 (J from scratch)
Step Two: i = 4, j = 0
Shit, suddenly found that the example of their choice is very bad, direct matching success, so, the guys themselves hand in hand.
Code: Https://github.com/coderchen/leetcode/blob/master/Implement_strStr.cpp