Chapter 9 · Simulation

String Matching Algorithms

← Chapter 9

Press Prepare to begin.

Matches

No result yet.

Preprocessing

The selected algorithm's table appears here.

    String Matching Algorithms

    Brute force, KMP, Boyer-Moore and Rabin-Karp are compared step by step on the same text and pattern.

    How to use

    • Enter a text T (up to 24 characters) and a pattern P (up to 12 characters), then choose an algorithm.
    • Prepare generates all the steps; Next Step advances one step, Auto Play plays the remaining steps, and Reset clears the run.
    • The pattern row is drawn under the current alignment (shift). Green: the compared characters match; red: mismatch; blue: an occurrence was found.
    • The preprocessing panel shows the table the algorithm uses: the LPS table for KMP, the last-occurrence table for Boyer-Moore, and hash values for Rabin-Karp.

    Brute force

    Tries every shift from 0 to n − m and compares characters from left to right until a mismatch.

    Knuth-Morris-Pratt (KMP)

    The LPS table (longest proper prefix that is also a suffix) tells how far the pattern can fall back after a mismatch, so the text index never moves backwards.

    Boyer-Moore (bad-character rule)

    Compares from right to left. On a mismatch the pattern is shifted (by at least one position) so that the last occurrence in the pattern of the mismatched text character lines up with it.

    Rabin-Karp

    The rolling hash of each text window is compared with the hash of the pattern (base 256, mod 101). Only windows with equal hash values are verified character by character, which weeds out spurious matches.

    Complexity

    AlgorithmPreprocessingMatching (worst case)
    Brute force—O(n·m)
    KMPO(m)O(n)
    Boyer-Moore (bad character)O(m + σ)O(n·m); in practice often sublinear
    Rabin-KarpO(m)Expected O(n + m), worst case O(n·m)