Princeton University COS 226 Algorithms and Data Structures Spring 2004 Kevin Wayne DFA Construction for KMP Reference: Chapter 19, Algorithms in C, 2 nd Edition, Robert Sedgewick.
2 DFA Construction for KMP 0 b a aabaaabb Search Pattern Xpattern[1..j]jnext
3 DFA Construction for KMP 01 a b b0 a1 0 aabaaabb Search Pattern X 00 pattern[1..j]jnext 0
4 DFA Construction for KMP 01 aa 2 b b b0 a aabaaabb Search Pattern X 0 a11 0 pattern[1..j]jnext 0 0
5 DFA Construction for KMP 301 aa 2 b b b a b0 a aabaaabb Search Pattern X 0 ab0 a pattern[1..j]jnext 0 2 0
6 DFA Construction for KMP 34 a 01 aa 2 b b b b a b0 a aabaaabb Search Pattern X 0 ab0 aba1 a pattern[1..j]jnext
7 DFA Construction for KMP 34 aa 5 01 aa 2 b b b b b a b0 a aabaaabb Search Pattern abaa X 2 0 ab0 aba1 a pattern[1..j]jnext
8 DFA Construction for KMP 34 aa 56 a 01 aa 2 b b b b b b a b0 a aabaaabb Search Pattern abaa X 2 abaaa2 0 ab0 aba1 a pattern[1..j]jnext
9 DFA Construction for KMP 34 aa 56 a 01 aa 2 b b 7 b b b b a b a b0 a aabaaabb Search Pattern abaa X 2 abaaa2 abaaab3 0 ab0 aba1 a pattern[1..j]jnext
10 DFA Construction for KMP 34 aa 56 a 01 aa 2 b b 7 8 b b b a b b a b a b0 a abaa X 2 abaaa2 abaaab3 0 ab0 aba1 a abaaabb07 aabaaabb Search Pattern pattern[1..j]jnext
11 DFA Construction for KMP: Implementation Build DFA for KMP. n Takes O(M) time. Requires O(M) extra space to store next[] table. int X = 0; int[] next = new int[M]; for (int j = 1; j < M; j++) { if (p.charAt(X) == p.charAt(j)) { // char match next[j] = next[X]; X = X + 1; } else { // char mismatch next[j] = X + 1; X = next[X]; } DFA Construction for KMP (assumes binary alphabet)