ac自动机

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;}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值