DFA Construccion para KMP Reference Chapter 19 Algorithms

  • Slides: 11
Download presentation
DFA Construccion para KMP Reference: Chapter 19, Algorithms in C, 2 nd Edition, Robert

DFA Construccion para KMP Reference: Chapter 19, Algorithms in C, 2 nd Edition, Robert Sedgewick. Princeton University • COS 226 • Algorithms and Data Structures • Spring 2004 • Kevin Wayne • http: //www. Princeton. EDU/~cos 226

DFA Construction for KMP a Search Pattern a b a a a b j

DFA Construction for KMP a Search Pattern a b a a a b j pattern[1. . j] X next b a b 0 2

DFA Construction for KMP a a b Search Pattern a b a a a

DFA Construction for KMP a a b Search Pattern a b a a a b b j 0 pattern[1. . j] X 0 next 0 0 1 0 b 0 a 1 3

DFA Construction for KMP a Search Pattern a b a a a b b

DFA Construction for KMP a Search Pattern a b a a a b b j 0 1 a b 0 1 0 pattern[1. . j] a X 0 next 0 1 2 0 b 0 a 1 a 2 b 4

DFA Construction for KMP a a b 0 1 0 Search Pattern a b

DFA Construction for KMP a a b 0 1 0 Search Pattern a b a a a b 1 2 0 j 0 b 1 2 2 2 3 pattern[1. . j] a a b X 0 next 0 1 0 0 2 a b 0 a 1 a 2 b 3 b 5

DFA Construction for KMP a a b 0 1 0 Search Pattern a b

DFA Construction for KMP a a b 0 1 0 Search Pattern a b a a a b 1 2 0 2 2 3 j 0 b 1 2 3 3 4 0 pattern[1. . j] a a a b b a X 0 next 0 1 0 2 0 a b 1 a 2 b 3 a 4 b 6

DFA Construction for KMP a a b 0 1 0 Search Pattern a b

DFA Construction for KMP a a b 0 1 0 Search Pattern a b a a a b 1 2 0 2 2 3 3 4 0 j 0 b 1 2 3 4 4 5 0 pattern[1. . j] a a b b b a a a X 0 next 0 1 2 0 0 b a b 0 a b 1 a 2 b 3 a 4 a 5 b 7

DFA Construction for KMP a a b 0 1 0 Search Pattern a b

DFA Construction for KMP a a b 0 1 0 Search Pattern a b a a a b 1 2 0 2 2 3 3 4 0 4 5 0 j 0 b 1 2 3 4 5 5 6 3 pattern[1. . j] a a a b b a a a X 0 next 0 1 2 2 0 0 3 b a b 0 a b 1 a b 2 b 3 a 4 a 5 a 6 b 8

DFA Construction for KMP a a b 0 1 0 Search Pattern a b

DFA Construction for KMP a a b 0 1 0 Search Pattern a b a a a b 1 2 0 2 2 3 3 4 0 4 5 0 5 6 3 j 0 b 1 2 3 4 5 6 6 2 7 pattern[1. . j] a a a b b b a a a a a b X 0 next 0 1 2 2 3 0 2 0 0 3 2 b a b 0 a b 1 a b 2 b 3 a 4 a 5 a 6 b 7 b a 9

DFA Construction for KMP a a b 0 1 0 Search Pattern a b

DFA Construction for KMP a a b 0 1 0 Search Pattern a b a a a b 1 2 0 2 2 3 3 4 0 4 5 0 5 6 3 j 0 b 6 2 7 1 2 3 4 5 6 7 7 4 8 pattern[1. . j] a a a a b b b a a a b 0 a b 1 a b 2 a a a b b b next 0 1 2 2 3 0 0 2 0 0 3 2 4 a a b a a X 0 b 3 a 4 a 5 a 6 b 7 b 8 b a 10

DFA Construction for KMP: Implementation Build DFA for KMP. n n Takes O(M) time.

DFA Construction for KMP: Implementation Build DFA for KMP. n 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. char. At(X) == p. char. At(j)) { next[j] = next[X]; X = X + 1; } else { next[j] = X + 1; X = next[X]; } } // char match // char mismatch DFA Construction for KMP (assumes binary alphabet) 11