TExcelTAD
Home › Selected Topics: FFT, Strings, Parallelism & NP-Completeness › String Matching with Finite Automata

String Matching with Finite Automata

The naive matcher forgets what it has seen; Rabin-Karp compresses it into a hash. A third idea is to precompute, for every possible situation, what to do next. The "situation" after reading part of the text is captured by one number: how long a prefix of the pattern the text currently ends with. A finite automaton whose states are these numbers reads each text character exactly once and does constant work per character. The price is a table of (m+1)⋅∣Σ∣(m + 1) \cdot \lvert \Sigma \rvert entries, built once for the pattern.

The state: the longest matching prefix

For a string xx, let σ(x)\sigma(x) be the length of the longest prefix of PP that is a suffix of xx. This is the suffix function of PP. For $P = $ abacab:

xx b ab aba abacaba cabac
longest prefix of PP that is a suffix of xx (empty) ab aba aba abac
σ(x)\sigma(x) 0 2 3 3 4

PP occurs ending at text position ii exactly when σ(T[0..i])=m\sigma(T[0..i]) = m. So it suffices to maintain q=σ(T[0..i])q = \sigma(T[0..i]) as ii advances.

The transition function

The string-matching automaton for PP has states 0,1,…,m0, 1, \ldots, m, start state 0, accepting state mm, and transition function

δ(q,a)=σ(Pq a),\delta(q, a) = \sigma(P_q\, a),

where PqP_q is the prefix of length qq and PqaP_q a is that prefix followed by the character aa.

Theorem. If q=σ(T[0..i−1])q = \sigma(T[0..i-1]), then σ(T[0..i])=δ(q,T[i])\sigma(T[0..i]) = \delta(q, T[i]).

Proof sketch

Write x=T[0..i−1]x = T[0..i-1] and a=T[i]a = T[i]. Any prefix of PP that is a suffix of xaxa has the form PrP_r with Pr−1P_{r-1} a suffix of xx (when r≥1r \ge 1), so r−1≤σ(x)=qr - 1 \le \sigma(x) = q, which means PrP_r is also a suffix of PqaP_q a (both are suffixes of xaxa, and PqaP_q a is the longer one). Hence σ(xa)≤σ(Pqa)\sigma(xa) \le \sigma(P_q a). Conversely, PqaP_q a is a suffix of xaxa, so every prefix of PP that is a suffix of PqaP_q a is a suffix of xaxa: σ(Pqa)≤σ(xa)\sigma(P_q a) \le \sigma(xa).

So the matcher is one table lookup per character:

text
AUTOMATON-MATCH(T, delta, m)
1  q = 0
2  for i = 0 to len(T) - 1
3      q = delta[q][T[i]]
4      if q == m
5          report the shift i - m + 1

That is Θ(n)\Theta(n) time with every character read once, no backing up in the text, which suits streaming input.

Building the table

The direct way follows the definition: for each state qq and character aa, try k=min⁡(m,q+1)k = \min(m, q + 1) and decrease kk until PkP_k is a suffix of PqaP_q a. With up to mm candidates per entry and O(m)O(m) per suffix test, that is O(m3∣Σ∣)O(m^3 \lvert \Sigma \rvert) time. The program builds the table for abacab this way, counting character comparisons, prints it and runs the automaton.

python · try it yourself
def build_naive(P, alphabet):
    m, comps = len(P), 0
    delta = [{} for _ in range(m + 1)]
    for q in range(m + 1):
        for a in alphabet:
            s = P[:q] + a
            k = min(m, q + 1)
            while True:                       # is P[:k] a suffix of s?
                ok = True
                for j in range(k):
                    comps += 1
                    if P[j] != s[len(s) - k + j]:
                        ok = False
                        break
                if ok:
                    break
                k -= 1
            delta[q][a] = k
    return delta, comps

P, alphabet = "abacab", "abc"
delta, comps = build_naive(P, alphabet)
print("state  " + "  ".join(alphabet) + "   (prefix)")
for q, row in enumerate(delta):
    print(f"  {q}    " + "  ".join(str(row[a]) for a in alphabet) + f"   {P[:q] or '-'}")
print("comparisons to build:", comps)

T = "abacabacababacab"
q, states, found = 0, [], []
for i, c in enumerate(T):
    q = delta[q][c]
    states.append(q)
    if q == len(P):
        found.append(i - len(P) + 1)
print("text:  ", " ".join(T))
print("states:", " ".join(map(str, states)))
print("matches at shifts", found)
state  a  b  c   (prefix)
  0    1  0  0   -
  1    1  2  0   a
  2    3  0  0   ab
  3    1  2  4   aba
  4    5  0  0   abac
  5    1  6  0   abaca
  6    3  0  0   abacab
comparisons to build: 125
text:   a b a c a b a c a b a b a c a b
states: 1 2 3 4 5 6 3 4 5 6 3 2 3 4 5 6
matches at shifts [0, 4, 10]

The states after each character show the automaton keeping track of partial matches: after the first match (state 6) the next characters a c a b lead straight back to 6, because the end of abacab (ab) is again a beginning of the pattern. Overlapping occurrences are found without any special handling.

A faster construction

The table can be filled in O(m∣Σ∣)O(m \lvert \Sigma \rvert) time. In state qq, the character P[q]P[q] advances to q+1q + 1. Every other character behaves exactly as in the state π\pi, where π\pi is the length of the longest proper prefix of PP that is a suffix of PqP_q: the automaton "falls back" to the longest shorter partial match and continues from there. That fallback state is itself computed by running the automaton on P[1..q−1]P[1..q-1], one step per row:

text
BUILD-AUTOMATON(P, Sigma)
1  delta[0][a] = 0 for every a;  delta[0][P[0]] = 1
2  x = 0                               // the state reached by P[1 .. q-1]
3  for q = 1 to m
4      for each a in Sigma
5          delta[q][a] = delta[x][a]   // fall back
6      if q < m
7          delta[q][P[q]] = q + 1      // advance
8          x = delta[x][P[q]]

The state xx is exactly the value π[q−1]\pi[q-1] of the prefix function of the next lesson, The Knuth-Morris-Pratt Algorithm. KMP stores only that array, mm numbers, and computes the transitions on the fly; the automaton stores all (m+1)∣Σ∣(m + 1)\lvert \Sigma \rvert of them. For bytes (∣Σ∣=256\lvert \Sigma \rvert = 256) and long patterns, the table's size is the automaton method's real cost.

python · try it yourself
def build_fast(P, alphabet):
    m = len(P)
    delta = [{a: 0 for a in alphabet} for _ in range(m + 1)]
    delta[0][P[0]] = 1
    x = 0
    for q in range(1, m + 1):
        for a in alphabet:
            delta[q][a] = delta[x][a]
        if q < m:
            delta[q][P[q]] = q + 1
            x = delta[x][P[q]]
    return delta

def build_naive(P, alphabet):
    m = len(P)
    delta = [{} for _ in range(m + 1)]
    for q in range(m + 1):
        for a in alphabet:
            s, k = P[:q] + a, min(m, q + 1)
            while not s.endswith(P[:k]):
                k -= 1
            delta[q][a] = k
    return delta

for P in ["abacab", "aaaa", "abcabcabd", "acgtacgtta"]:
    alphabet = sorted(set(P) | {"z"})
    print(f"{P:11} tables agree: {build_fast(P, alphabet) == build_naive(P, alphabet)},",
          f"entries: {(len(P) + 1) * len(alphabet)}")
abacab      tables agree: True, entries: 28
aaaa        tables agree: True, entries: 10
abcabcabd   tables agree: True, entries: 50
acgtacgtta  tables agree: True, entries: 55

In C++

The automaton matcher in C++ over a byte alphabet, built with the fast construction: a table of (m+1)×256(m + 1) \times 256 integers, then one lookup per text character.

cpp · try it yourself
#include <array>
#include <cstdio>
#include <string>
#include <vector>

using Table = std::vector<std::array<int, 256>>;

Table build(const std::string& P) {
    int m = int(P.size());
    Table delta(m + 1);
    for (auto& row : delta) row.fill(0);
    delta[0][(unsigned char)P[0]] = 1;
    int x = 0;
    for (int q = 1; q <= m; q++) {
        delta[q] = delta[x];                                   // fall back
        if (q < m) {
            delta[q][(unsigned char)P[q]] = q + 1;             // advance
            x = delta[x][(unsigned char)P[q]];
        }
    }
    return delta;
}

int main() {
    std::string P = "abacab", T = "abacabacababacab";
    Table delta = build(P);
    int q = 0, m = int(P.size());
    std::printf("states:");
    for (size_t i = 0; i < T.size(); i++) {
        q = delta[q][(unsigned char)T[i]];
        std::printf(" %d", q);
        if (q == m) std::printf("*");
    }
    std::printf("\n* marks a match ending there; table has %zu entries\n", delta.size() * 256);
}
states: 1 2 3 4 5 6* 3 4 5 6* 3 2 3 4 5 6*
* marks a match ending there; table has 1792 entries

Test yourself

What does the state qq of the string-matching automaton mean after reading T[0..i]T[0..i]?

  1. The number of matches so far
  2. The length of the longest prefix of PP that is a suffix of T[0..i]T[0..i]
  3. The position of the last mismatch
  4. The hash of the window

For $P = $ abacab, what is δ(3,c)\delta(3, c)?

  1. 0
  2. 1
  3. 3
  4. 4

What is the matching time of the automaton method, once the table is built?

  1. Θ(n)\Theta(n)
  2. Θ(nm)\Theta(nm)
  3. Θ(n∣Σ∣)\Theta(n \lvert \Sigma \rvert)
  4. Θ(nlg⁡m)\Theta(n \lg m)

How large is the transition table for a pattern of length mm over an alphabet Σ\Sigma?

  1. mm entries
  2. (m+1)∣Σ∣(m + 1)\lvert \Sigma \rvert entries
  3. m2m^2 entries
  4. 2m2^m entries