AC 可以引用同时匹配多个模式串的场景中, 现将C 实现代码贴下,代码不是很规范,请包涵。
如个实现上任何不当之处,欢迎指正。
#define NULL 0
#define PTYPE_AC char*
#define get_idx(x) ((x)-'a')
const int K = 26;// 26个字母
typedef struct _node{
struct _node *child[K];
struct _node *fail;
int isWord; // 0-NO, >=1-YES.
_node(): fail(0), isWord(0) { memset(child, 0, sizeof(_node*)*K); }
} node;
node *pool[K*K*K]; // 用于 BFS 方式建立AC-fail关系。
void insert(node* root, const PTYPE_AC arr){
if(!arr)
return;
if(!root)
root = new node();
node *tmp = root;
while(*arr){
int idx = get_idx(*arr++);
if(!tmp->child[idx])
tmp->child[idx] = new node();
tmp = tmp->child[idx];
}
tmp->isWord = 1;
return;
}
void buildACFail(node* root){
if(!root)
return;
root->fail = NULL;
node *tmp = root;
int head = 0, tail = 0;
pool[head++] = root;
while(head != tail){
node *tmp = pool[tail++];
for(int i = 0; i < K; ++i){
node *sub = tmp->child[i];
if(!sub) // 无效子节点。
continue;
while(tmp->fail && !tmp->fail->child[i])
tmp = tmp->fail;
if(!tmp->fail){ // root.
sub->fail = root;
} else {
sub->fail = tmp->fail->child[i]; // tmp->child[i] 失效,则跳到 tmp->fail->child[i].
}
pool[head++] = sub; // 加入等待遍历其子节点的队列}}}// 基于AC机 统计有多少不同的词被命中int query(node *root, const PTYPE_AC str){if(!root || !str)return -1;node *tmp = root;int cnt = 0;for(int idx = get_idx(*str); *str != '\0'; ++str){ // 遍历主串if(tmp->child[idx]){node *anode = tmp->child[idx];if(anode->isWord == 1){++cnt; // 第一次命中该词++anode->isWord; // 指示已经命中这个词,不再重复统计 而且由于该树枝对应的词串前缀已被使用做命中串 故跳回rootanode = root;}tmp = anode;} else {if(tmp->fail) // 非 root-node.tmp = tmp->fail;}}return cnt;}