简体   繁体   中英

How can I check if my line matches the NFA?

I made NFA that makes from regular expressions 3d array, for example (01*) expression. I get it:

[[FROM,TO,TRANSITION]]

    [['q0', 'q1', '0'], ['q1', 'q2', ':e:'] ,['q1', 'q4', ':e:'] ,
    ['q2', 'q3', '1'], ['q3', 'q2', ':e:'], ['q3', 'q4', ':e:']

How do I write a method that can test a string that satisfies this automaton? For example "011111" will return q0 q1 q2 q3 q2 q3 q2 q3 q2 q3 q2 q3 q4

  1. You can convert the automaton to DFA (after that checking becomes trivial). This approach is useful is the NFA is small but the number of strings you're going to test is pretty big.

  2. You can also build a new graph where each vertex is pair (state of the NFA, position in the string). There's an edge between a state and another state for each position if it's an epsilon transition. There's also an edge (s, pos) -> (s', pos + 1) if the character for the s->s' transition in the automaton matches the character at position pos in the string.
    After building the graph, you just need to check that a pair (t, string.length()) is reachable for at least one terminal state t (you can use any graph traversal algorithm to check it, for instance a depth-first search).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM