Dahua Data Structure 12: pattern matching of strings (BM algorithm)

Source: Internet
Author: User
Tags comparison

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.

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.