12.07.2015 Views

Building an NFA and Pattern Matching

Building an NFA and Pattern Matching

Building an NFA and Pattern Matching

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Algorithm for simulating <strong>NFA</strong> M = (Q, Σ, ∆, S, F )without ɛ-tr<strong>an</strong>sitions:P = S; /* P = set containing all start states */while (input not empty) {sc<strong>an</strong>(c);T = ∅;for (each ∆(q, c) where q ∈ P )T = T ∪ ∆(q, c);if (T ⊆ ∅) /* blocked */reject;P = T ;}accept iff (P ∩ F ≠ ∅);5


Algorithm for simulating <strong>NFA</strong> with ɛ-tr<strong>an</strong>sitions:P = S;while (true) {do {T = P ;for (each ∆(q, ɛ) where q ∈ P )P = P ∪ ∆(q, ɛ);} while (T ≠ P ); /* loop again if P modified */if (input empty)break;sc<strong>an</strong>(c);T = ∅;for (each ∆(q, c) where q ∈ P )T = T ∪ ∆(q, c);if (T ⊆ ∅)reject;P = T ;}accept iff (P ∩ F ≠ ∅);6


Data structure for <strong>NFA</strong>interface Label {boole<strong>an</strong> match(char c);boole<strong>an</strong> epsilon(); // true iff e-tr<strong>an</strong>sition}class Edge {Integer src, dst;Label label;}// source, destinationclass <strong>NFA</strong> {Set S, F; // start, final statesSet edges; // digraph<strong>NFA</strong>(String regex) {..}boole<strong>an</strong> accept(String input) {..}}7


oole<strong>an</strong> accept(String input) {Set P = new HashSet(S);int i = 0;while (true) {boole<strong>an</strong> ch<strong>an</strong>ged;do {ch<strong>an</strong>ged = false;for (Edge e : edges)if (e.label.epsilon() && P.contains(e.src))ch<strong>an</strong>ged = ch<strong>an</strong>ged || P.add(e.dst);} while (ch<strong>an</strong>ged);if (i >= input.length()) break;char c = input.charAt(i++);Set T = new HashSet();for (Edge e : edges)if ((e.label.match(c) && P.contains(e.src))T.add(e.dst);}if (T.isEmpty()) return false;P = T;}for (Integer q : P)if (F.contains(q)) return true;return false;8

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!