Algorithms · String Matching with a Finite Automaton and Boyer-Moore
Boyer-Moore: the bad-character rule
Boyer-Moore compares the pattern against the text right to left within each alignment, and on a mismatch shifts the pattern by more than one using two heuristics: the bad-character rule and the good-suffix rule. GATE concentrates on the bad-character rule.
3.1 The rule in one line
If, at alignment , the mismatch occurs at pattern position (1-based from the left) against text character , then:
- If occurs in to the left of position , let be the rightmost such occurrence; shift the pattern so that aligns with . Shift amount .
- If does not occur in , shift the pattern past the mismatching character: shift .
- If occurs only to the right of , the bad-character rule gives a non-positive shift; use a shift of (in the full algorithm, take the max with the good-suffix shift, which is always ).
The preprocessing is a table = index of the last (rightmost) occurrence of in , or if absent. Then the shift is . This simple textbook form can shift less than the "rightmost occurrence left of " rule above when also occurs to the right of in (then and the shift is ).
3.2 Worked example
ababaca (), abababacaba (). Last-occurrence table: a→7, b→4, c→6; all others 0.
Indices: and . Align at shift and compare from the right.
T: a b a b a b a c a b a
P: a b a b a c a (s = 0)
^ j = 6: T[6]=b, P[6]=c (P[7]=a=T[7] matched first)
matches, then : mismatch at with , . Shift (2 comparisons so far).
Align at :
T: a b a b a b a c a b a
P: a b a b a c a (s = 2)
Right to left: ✓, ✓, ✓, ✓, ✓, ✓, ✓. Match at shift 2 ( ababaca).
Boyer-Moore used 2 alignments (2 + 7 = 9 character comparisons); the naive algorithm uses 3 alignments (shifts 0, 1, 2) and comparisons. The first alignment shifted by 2 after only two comparisons.
3.3 Complexity
- Preprocessing (bad-character table): .
- Matching with the bad-character rule alone: worst case (for example , : every alignment costs comparisons and shifts by only ).
- With both heuristics (original Boyer-Moore): when the pattern does not occur in the text, but still worst case when the pattern occurs many times (e.g. , ). Adding Galil's rule makes the worst case always. In practice it is sublinear, with best case comparisons.
Comparison of the five algorithms
| Algorithm | Preprocessing | Matching | Worst case total | Extra space | Direction |
|---|---|---|---|---|---|
| Naive | left→right | ||||
| Rabin–Karp | expected, worst | left→right | |||
| Finite automaton | left→right | ||||
| KMP | left→right | ||||
| Boyer–Moore | best case | if matches are frequent; if pattern absent or with Galil's rule | right→left |
Key contrasts to memorise: the automaton is the only one whose matching phase is with no dependence on at all, but it pays space. KMP achieves the same total time with only space by computing fallbacks on the fly. Boyer–Moore is the fastest in practice because it skips text.