-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathAhoCorasick.cpp
128 lines (101 loc) · 2.44 KB
/
AhoCorasick.cpp
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
class AhoCorasick
{
public:
struct Node
{
Node() : matched(0), fail(0)
{
memset(next, -1, sizeof(next));
}
int next[26];
int matched;
int fail;
};
class Matcher
{
public:
Matcher(const AhoCorasick& ac_) : ac(ac_), now(0)
{
}
int matched() const
{
return ac.getNode(now).matched;
}
void move(char c)
{
int v = now;
while (v != 0 && ac.getNode(v).next[c - 'a'] == -1)
v = ac.getNode(v).fail;
if (ac.getNode(v).next[c - 'a'] != -1)
v = ac.getNode(v).next[c - 'a'];
now = v;
}
private:
int now;
const AhoCorasick& ac;
};
AhoCorasick()
{
nodes.emplace_back();
}
void build(const vector<string>& patterns)
{
for (auto& p : patterns)
insert(0, p, 0);
bfs();
}
Node getNode(int idx) const
{
return nodes[idx];
}
Matcher match() const
{
return Matcher(*this);
}
private:
void insert(int vertex, const string& pattern, int idx)
{
if (idx == pattern.size())
{
nodes[vertex].matched++;
return;
}
if (nodes[vertex].next[pattern[idx] - 'a'] == -1)
{
nodes.emplace_back();
nodes[vertex].next[pattern[idx] - 'a'] = nodes.size() - 1;
}
insert(nodes[vertex].next[pattern[idx] - 'a'], pattern, idx + 1);
}
void bfs()
{
queue<int> q;
q.push(0);
while (!q.empty())
{
auto now = q.front();
q.pop();
for (int i = 0; i < 26; i++)
{
if (nodes[now].next[i] == -1)
continue;
int next = nodes[now].next[i];
q.push(next);
int p = now;
if (p == 0)
{
nodes[next].fail = p;
continue;
}
p = nodes[now].fail;
while (p != 0 && nodes[p].next[i] == -1)
p = nodes[p].fail;
if (nodes[p].next[i] != -1)
p = nodes[p].next[i];
nodes[next].fail = p;
nodes[next].matched += nodes[p].matched;
}
}
}
vector<Node> nodes;
};