相关资源下载: http://download.youkuaiyun.com/source/2224206
AC 算法 [1]
解决问题:文本 text 是否匹配模式集合 s (例如 s = {"he", "she", "his", "hers"}) 中的一个
或者多个模式。
基本思路:匹配失败时回退到适合位置(与 KMP 的思想类似)
以下举例说明AC算法的思路
模式集合{ "he", "she", "his", "hers"}
// ----------------------------------------------------------
构图
1. 初始化时
Fig 1
2. 插入 "he"
Fig 2
添加 h 时state(状态)由 0 变为 1,添加 e 时state 由 1 变为 2,当匹配到 state = 2 时就表示匹配到了"he",于是把state = 2 与 "he" 绑定。
3. 插入 "she"
Fig 3
解释同(2), state = 5 与 "she" 绑定。
4. 插入 "his"
Fig 4
添加 h,但途中已经存在 "h",所以在原有节点上继续添加"is", state = 7 与 "his" 绑定。
5. 插入 "hers"
Fig 5
图上已存在 "he",所以在原有节点上继续添加"es",state = 9 与 "hers" 绑定。
// ----------------------------------------------------------
g(state, a): 表示状态state 插入字符a 后的状态
比如: g(4, e) = 5, g(0, h) = 1
output(state): 表示与状态state绑定的某些模式。
比如: output(5) = "she", output(2) = "he", 但 output(1) 为空
以下是生成 g(state, a), 部分output(state)的算法
begin
queue = empty
for each symbol a do
begin
next(0, a) = g(0, a)
if g(0, a) != 0 then queue.add(g(0, a))
end
while queue != empty do
begin
r = queue.front(); queue.pop()
/* 分两种情况 */
for each symbol a do
if g(r, a) = s != fail do
begin
queue.add(s)
next(r, a) = s
end
else
next(r, a) = next(f(r), a)
end
end
// -----------------------------------------------------------------