In the previous article, I introduced the KMP algorithm.
However, it is not the most efficient algorithm, the actual use is not much. A variety of text editor "lookup" function (ctrl+f), mostly using Boyer-moore algorithm.
Boyer-moore algorithm is not only high efficiency, but also ingenious and easy to understand. In 1977, Professor Robert S. Boyer of the University of Texas and Professor J Strother Moore invented the algorithm.
Below, I explain this algorithm based on Professor Moore's own example.
1.
The string is assumed to be a simple EXAMPLE and the search term is "EXAMPLE".
2.
First, the string is aligned with the search term header and is compared from the tail.
This is a very smart idea, because if the trailing characters do not match, then you can know that the first 7 characters are definitely not the result of the search if you compare them one at a time.
We see that "S" does not match "E". At this point, "S" is referred to as "bad character" (character), which is a mismatched character. We also found that "s" is not included in the search term "EXAMPLE", which means that the search term can be moved directly to the latter of "s".
3.
Still from the tail start comparison, found that "P" and "E" does not match, so "P" is "bad character." However, "P" is included in the search term "EXAMPLE". So, move the search word back two digits, two "P" alignment.
4.
We have thus summed up the "bad character rule":
Post shift = position of bad character-last occurrence in a search term
If the "bad character" is not included in the search term, the last occurrence is-1.
Take "P" as an example, which appears as a "bad character" in the 6th bit of the search term (numbered from 0), and the last occurrence in the search term is 4, so it moves back 6-4 = 2 digits. Take the second step of "S" in the previous example, it appears in the 6th bit, the last occurrence of the position is-1 (that is, not appear), then the entire search word after 6-(-1) = 7-bit.