Boyer-moore algorithm for string matching

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.