1. KMP Algorithm Introduction:
KMP algorithm is an improved string matching algorithm, compared to the naïve algorithm, the KMP algorithm has calculated a hash table to guide the match in the process of failure to try the next match after the start position, so as to avoid repetitive reading and matching process. This hash table is called a "partial matching value table" (particial match table), which is the most subtle of the KMP algorithm.
2. KMP Algorithm Analysis:
The following is an article in Nanyi's blog to analyze the principle of the KMP algorithm: there is a string "BBC Abcdab Abcdabcdabde", I want to know if it contains another string "Abcdabd"?
(1) First, the string "BBC Abcdab Abcdabcdabde" is compared with the first character of the search term "abcdabd". Because B does not match A, the search term is moved one bit after the other.
(2) because B does not match A, the search term moves backwards.
(3) So until the string has a character, the same as the first character of the search term.
(4) Then compare the string and the next character of the search term, or the same.
(5) until the string has a character that is not the same as the corresponding character in the search term.
(6) At this point, the most natural response is to move the search word one after the other, and then compare from the beginning. It works, but it's inefficient, because you have to move the "search position" to a position you've already compared.