-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNFA.java
More file actions
89 lines (78 loc) · 2.54 KB
/
Copy pathNFA.java
File metadata and controls
89 lines (78 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
* Sample usage: java NFA (A*B|AC)D AAAABD
* true
*
* Sample usage: java NFA (A*B|AC)D AAAAC
* false
*
* Sample usage: java NFA (a|(bc)*d)* abcbcd
* true
*
* Sample usage: java NFA (a|(bc)*d)* abcbcbcdaaaabcbcdaaaddd
* true
*/
public class NFA {
private char[] re; // match transitions
private Digraph G; // epsilon transitions
private int M; // number of states
public NFA(String regexp){
// Create the NFA for the given regular expression.
LinkedStack<Integer> ops = new LinkedStack<>();
re = regexp.toCharArray();
M = re.length;
G = new Digraph(M+1);
for (int i=0; i<M; i++){
int lp = i; // (might be) left paren
if (re[i] == '(' || re[i] == '|')
ops.push(i);
else if (re[i] == ')'){
int or = ops.pop(); // (might be) or
// 2-way or operator
if (re[or] == '|'){
lp = ops.pop();
G.addEdge(lp, or+1);
G.addEdge(or, i);
}
else lp = or;
}
// closure operator (uses 1-character lookahead)
if (i<M-1 && re[i+1] == '*'){
G.addEdge(lp, i+1);
G.addEdge(i+1, lp);
}
if (re[i] == '(' || re[i] == '*' || re[i] == ')')
G.addEdge(i, i+1);
}
}
// Returns true if the text is matched by the regular expression.
public boolean recognizes(String txt){
LinkedBag<Integer> pc = new LinkedBag<>();
DirectedDFS dfs = new DirectedDFS(G, 0);
for (int v=0; v<G.V(); v++)
if (dfs.marked(v))
pc.add(v);
// Compute possible NFA states for txt[i+1]
for (int i = 0; i<txt.length(); i++){
LinkedBag<Integer> match = new LinkedBag<>();
for (int v : pc)
if (v<M)
if (re[v] == txt.charAt(i) || re[v] == '.')
match.add(v+1);
pc = new LinkedBag<>();
dfs = new DirectedDFS(G, match);
for (int v=0; v<G.V(); v++)
if (dfs.marked(v))
pc.add(v);
}
// check for accept state
for (int v : pc)
if (v==M) return true;
return false;
}
public static void main(String[] args){
String regexp = '(' + args[0] + ')';
String txt = args[1];
NFA nfa = new NFA(regexp);
StdOut.println(nfa.recognizes(txt));
}
}