1. BM Algorithm Introduction:
KMP algorithm is not the most efficient string matching algorithm, the actual application is not much, the various text editor "find" function is mostly using BM algorithm (Boyer Moore). BM algorithm is more efficient and easier to understand.
2. BM Algorithm Analysis:
(1) Assuming that the string is ' here's A simple EXAMPLE ', the search term is ' EXAMPLE '.
(2) First, "string" and "search term" head alignment, starting from the tail to compare. This is a very smart idea, because if the trailing characters do not match, then the first 7 characters (as a whole) are definitely not the result 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 summed up the "bad character rule":
Post shift = position of bad character-last occurrence of position value in 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.
(5) Still starting from the tail of the comparison, "E" and "E" match.
(6) Compare the previous one, "le" and "le" match.