Proofs: Computing the string-matching automaton transition function
These are the human proofs of Computing the string-matching automaton transition function, at full length.
The lagging-state construction computes the transition function full
This proof shows: correctness, termination.
Claim. For a pattern over , COMPUTE-TRANSITION-FUNCTION stops and returns with for all and all .
Here is the length of the longest prefix of that is a suffix of . We use the recursion proved on the page of the string-matching automaton: if , then .
Termination. All loops are bounded: iterations of line L4 with iterations of line L5 each.
Row 0. is 1 if and 0 otherwise, which is what lines L1 and L2 set. For , is always 0 and line L1 sets row 0 to zeros.
Invariant. At the start of the iteration for ():
(I) rows are correct, and .
For , row 0 is correct and of the empty string.
Lemma 1. , so row is correct by (I).
Proof. .
Lemma 2. Let and let be a character, with if . Then .
Proof. Write and , the string without its first character. Let . If , then and , so , which is excluded. So , and a suffix of of length at most is a suffix of . Hence . The other inequality holds because every suffix of is a suffix of .
Step. For each handled by lines L5 and L6 and not overwritten by line L8, Lemma 2, the recursion with and Lemma 1 give
If , line L8 sets , which is correct because is a suffix of itself and no prefix of is longer than characters while ending . Line L9 sets to , which by the recursion equals . Row read here was already correct before the iteration and is not changed by it, since . So (I) holds for . At the end, (I) for is the claim.
Back to Computing the string-matching automaton transition function