Short answer: Boyer-Moore aligns the pattern with the text and compares from the right end of the pattern. The bad-character rule shifts so that the mismatched text character lines up with its rightmost occurrence in the pattern, or shifts past the pattern if the character does not occur. The good-suffix rule shifts by a border of the suffix that already matched. Together they never miss a match, and on natural language they often examine fewer than n text characters. The worst case of a direct implementation is O(nm), which Galil’s stopping rule brings back to linear.
What the problem actually asks
KMP always reads the next text character. When the alphabet is large and the pattern is long, the last character of the current alignment is likely to disagree immediately and to tell the scan how far it can jump. Comparing from the right harvests that information on the first look.
Two shifts are computed, and the algorithm takes the larger one. The bad-character shift depends on the mismatched character and its last position in the pattern. The good-suffix shift depends only on how long a suffix matched, and it is a table built from the pattern, related to the prefix table computed on the reversed pattern.
What the algorithm guarantees
Every match is reported if the shift is the maximum of the two legal shifts and is at least one. The preprocessing of both tables is O(m + σ), where σ is the alphabet size. A naive shift loop can still compare Θ(nm) characters on a repetitive pattern such as a string of identical letters, because an overlapping match reexamines the same text. Galil’s optimization remembers a substring already known to match and does not compare it again, restoring an O(n + m) worst case.
The practical speed on natural-language text is the reason the algorithm, and its Horspool simplification that keeps only the bad-character rule on the last pattern character, shows up in library searches. Horspool is not the full Boyer-Moore rule set. It is often faster and still correct.
The working steps
- Build the bad-character table: for each alphabet character, the rightmost index where it appears in the pattern, or −1 if it does not appear.
- Build the good-suffix table from the borders of the pattern’s suffixes, so a matched suffix of length k knows a safe shift.
- Align the pattern at text position 0. Compare pattern characters from the end backward.
- On a full match, report it and shift by the good-suffix rule for a full match, which is the period. On a mismatch at pattern index j against text character c, shift by the maximum of the bad-character shift for c and the good-suffix shift for the matched tail.
- Repeat until the alignment runs off the text. Apply Galil’s rule if the worst case must be linear.
Sublinear comparisons are a typical-case statement about large alphabets, not a worst-case promise of the textbook loop. KMP is the algorithm that is linear without an extra stopping rule. Boyer-Moore is also not an approximate matcher. A small edit distance uses a different automaton, such as bitap.
Approaches that look simpler and fail
| Approach | Why it fails when only one of the two shifts is applied incorrectly |
|---|---|
| Shift by the distance to the mismatched character’s leftmost occurrence | The rightmost occurrence inside the pattern is the one that keeps a possible match. The leftmost occurrence can skip a real alignment. |
| Shift backward when the bad-character occurrence lies to the right of the mismatch | The alignment must move forward. A negative bad-character shift is replaced by the good-suffix shift, or by one, so the scan progresses. |
| Quote O(n + m) for the version that recompares overlapping matches | That version is O(nm) on repetitive strings. Galil’s rule is the linear repair. |
| Use Horspool’s single-character shift and call it the good-suffix rule | Horspool looks up the text character aligned with the pattern’s end, whether or not it matched. It is a correct simplification and a different table. |
A guaranteed linear forward scan is KMP. Many patterns at once are Aho-Corasick. Boyer-Moore is the right-to-left skip, with Horspool as the usual practical reduction.
A working example
This Python fragment shifts by the bad-character rule, using the rightmost occurrence of the mismatched text character. It still checks the aligned window, so a large shift cannot hide a match. needle starts at index 7 in this haystack.
def boyer_moore(text, pat):
last = {ch: i for i, ch in enumerate(pat)}
i = 0
while i <= len(text) - len(pat):
j = len(pat) - 1
while j >= 0 and pat[j] == text[i + j]:
j -= 1
if j < 0:
return i
ch = text[i + j]
shift = j - last.get(ch, -1)
i += max(1, shift)
return -1
hay = "find a needle"
assert boyer_moore(hay, "needle") == hay.index("needle") == 7
print(boyer_moore(hay, "needle"))
Where it is used
GNU grep and a long line of text editors use Boyer-Moore, or its Horspool simplification, to skip ahead on a mismatch. The bad-character table is why a long pattern can jump. A short pattern or many patterns at once favor a different automaton.
When you can drop this algorithm
Drop full Boyer-Moore when Horspool or a library memmem is already as fast on the alphabet you have. Keep the full two-rule algorithm when good suffixes of a repetitive pattern actually pay for the extra table, and add Galil’s rule when the worst case must be linear.
Why this stays published
We publish this so a search for Boyer-Moore returns the right-to-left comparison, the two shift rules, and the quadratic worst case of the version that recompares overlaps. Boyer-Moore searches by comparing from the right and shifting by the bad-character and good-suffix rules, which is fast on large alphabets and quadratic in the worst case unless overlapping recomparisons are suppressed.
本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。
