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 entries, built once for the pattern.
The state: the longest matching prefix
For a string , let be the length of the longest prefix of that is a suffix of . This is the suffix function of . For $P = $ abacab:
b |
ab |
aba |
abacaba |
cabac |
|
|---|---|---|---|---|---|
| longest prefix of that is a suffix of | (empty) | ab |
aba |
aba |
abac |
| 0 | 2 | 3 | 3 | 4 |
occurs ending at text position exactly when . So it suffices to maintain as advances.
The transition function
The string-matching automaton for has states , start state 0, accepting state , and transition function
where is the prefix of length and is that prefix followed by the character .
Theorem. If , then .
Proof sketch
Write and . Any prefix of that is a suffix of has the form with a suffix of (when ), so , which means is also a suffix of (both are suffixes of , and is the longer one). Hence . Conversely, is a suffix of , so every prefix of that is a suffix of is a suffix of : .
So the matcher is one table lookup per character:
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 + 1That is 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 and character , try and decrease until is a suffix of . With up to candidates per entry and per suffix test, that is time. The program builds the table for abacab this way, counting character comparisons, prints it and runs the automaton.
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 time. In state , the character advances to . Every other character behaves exactly as in the state , where is the length of the longest proper prefix of that is a suffix of : 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 , one step per row:
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 is exactly the value of the prefix function of the next lesson, The Knuth-Morris-Pratt Algorithm. KMP stores only that array, numbers, and computes the transitions on the fly; the automaton stores all of them. For bytes () and long patterns, the table's size is the automaton method's real cost.
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 integers, then one lookup per text character.
#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 of the string-matching automaton mean after reading ?
- The number of matches so far
- The length of the longest prefix of that is a suffix of
- The position of the last mismatch
- The hash of the window
For $P = $ abacab, what is ?
- 0
- 1
- 3
- 4
What is the matching time of the automaton method, once the table is built?
How large is the transition table for a pattern of length over an alphabet ?
- entries
- entries
- entries
- entries