//NFA
import edu.princeton.cs.algs4.*;
public class NFA {
private Digraph G;
private char[] ch;
private int N;
public NFA(String regexp) {
Stack<Integer> ops = new Stack<>();
ch = regexp.toCharArray();
this.N = regexp.length();
G = new Digraph(N + 1);
for (int i = 0 ; i < N ; i++) {
int bracket = i;
if (ch[i] == '(' || ch[i] == '|') ops.push(i);
else if (ch[i] == ')') {
int or = ops.pop();
if (or == '|') {
bracket = ops.pop();
G.addEdge(bracket, or + 1);
G.addEdge(or, i);
}else bracket = or;
}
if (i < N-1 && ch[i+1] == '*') {
G.addEdge(bracket, i + 1);
G.addEdge(i + 1,bracket);
}
if (ch[i] == '*' || ch[i] == '(' || ch[i] == ')') G.addEdge(i, i + 1);
}
}
public boolean recognizes(String txt) {
Bag<Integer> pc = new Bag<>();
DirectedDFS dfs = new DirectedDFS(G, 0);
for (int v = 0 ; v < G.V();v++) {
if (dfs.marked(v)) pc.add(v);
}
for (int i = 0; i < txt.length();i++) {
Bag<Integer> match = new Bag<>();
for (int v : pc) {
if (v < N) {
if (ch[v] == txt.charAt(i) || ch[v] == '.') {
match.add(v);
}
}
}
pc = new Bag<>();
dfs = new DirectedDFS(G, match);
for (int v = 0 ; v < G.V();v++) {
if (dfs.marked(v)) pc.add(v);
}
}
for (int v : pc) if (v == N) return true;
return false;
}
}
算法 5.4 正则表达式的实现
最新推荐文章于 2024-06-02 20:13:23 发布