字典树(AC自动机)的两种实现方式

在这里插入图片描述
字典树主要用与字符串的保存,,查询。
第一个:使用数组;

将根结点编号为0,然后把其余结点(包括叶子节点和非叶子节点)编号为从1开始的正整数,然后用一个数组来保存每个结点的所有子节点,用下标直接存取。

ch[i][j]保存结点i的那个编号为j的子结点的编号什么叫“编号为j”呢?比如,若是处理全部
由小写字母组成的字符串,把所有小写字母按照字典序编号为0,1,2,…,则ch[i][0]表示结点编号为i的a的下一个节点的编号。如果这个子结点不存在,则ch[i][0]=0。
sigma_size表示字符集的大小,比如,当字符集为全体小写字母时,sigma_size=26。
maxnode:表示节点的总个数
val[i]>0当且仅当结点i是单词结点。每个字符串有一个权值,就可以把这个权值保存在val[i]中。:val[i] ,一维数组,我当时考虑的是"abc" 和“abd”种情况,和“app”和“application”这两种情况,其实不用考虑,
解释"abc",“abd”;前两个是公用的ab,b这个节点所在编号的c的编号和d 下的编号是不同的,(c是一个节点有一个编号,d也是一个节点,也有一个编号,编号是不同的,所以,用编号就可以代表一个不同的字符,)对于单词而言只有末尾的那个字符对应的编号是有权值的,

		struct Trie
		{
		    int ch[maxnode][26];
		    int val[maxnode];
		    int sz; // 结点总数
		    void clear()
		    {
		        sz = 1;    // 初始时只有一个根结点
		        memset(ch[0], 0, sizeof(ch[0]));
		    }
		    int idx(char c)
		    {
		        return c - 'a';    // 字符c的编号
		    }
		
		    // 插入字符串s,附加信息为v。注意v必须非0,因为0代表“本结点不是单词结点”
		    void insert(const char *s, int v)
		    {
		        int u = 0, n = strlen(s);
		        for(int i = 0; i < n; i++)
		        {
		            int c = idx(s[i]);
		            if(!ch[u][c])   // 结点不存在
		            {
		                memset(ch[sz], 0, sizeof(ch[sz]));
		                val[sz] = 0;  // 中间结点的附加信息为0
		                ch[u][c] = sz++; // 新建结点
		            }
		            u = ch[u][c]; // 往下走
		        }
		        val[u] = v; // 字符串的最后一个字符的附加信息为v
		    }
		
		    // 找字符串s的长度不超过len的前缀
		    void find_prefixes(const char *s, int len, vector<int> &ans)
		    {
		        int u = 0;
		        for(int i = 0; i < len; i++)
		        {
		            if(s[i] == '\0') break;
		            int c = idx(s[i]);
		            if(!ch[u][c]) break;
		            u = ch[u][c];
		            if(val[u] != 0) ans.push_back(val[u]); // 找到一个前缀
		        }
		    }
		};

第二种是树:

		#include <bits/stdc++.h>
		using namespace std;
		
		struct node{
			node* next[26];
			node* fail;
			int cnt;
			node(){
				for (int i = 0; i <26; ++i)next[i] = NULL;
				cnt = 0;
				fail = NULL;
			}
		}*q[500010];
		
		node *root;
		int head, tail;
		char str[1000005];
		
		void insert(char *str)
		{
			node *p = root;
			int i = 0, index;
			while (str[i]){
				index = str[i] - 'a';
				if (p->next[index] == NULL)p->next[index] = new node();
				p = p->next[index];
				++i;
			}
			++p->cnt;
		}
		
		void build(node* root)
		{
			root->fail = NULL;
			q[tail++] = root;
			while (head < tail){
				node* temp = q[head++];
				node* p = NULL;
				for (int i = 0; i < 26; ++i){
					if (temp->next[i] != NULL){
						if (temp == root)temp->next[i]->fail = root;
						else{
							p = temp->fail;
							while (p != NULL){
								if (p->next[i] != NULL){
									temp->next[i]->fail = p->next[i];
									break;
								}
								p = p->fail;
							}
							if (p == NULL)temp->next[i]->fail = root;
						}
						q[tail++] = temp->next[i];
					}
				}
			}
		}
		
		int query(node *root)
		{
			int i = 0, cnt = 0, index;
			node* p = root;
			while (str[i]){
				index = str[i] - 'a';
				while (p->next[index] == NULL && p != root)p = p->fail;
				p = p->next[index];
				if (p == NULL)p = root;
				node* temp = p;
				while (temp != root && temp->cnt != -1){
					cnt += temp->cnt;
					temp->cnt = -1;
					temp = temp->fail;
				}
				++i;
			}
			return cnt;
		}
		
		int main()
		{
			int t, n;
			scanf("%d", &t);
			while (t--){
				head = tail = 0;
				root = new node();
				scanf("%d", &n);
				while(n--){
					scanf("%s", str);
					insert(str);
				}
				build(root);
				scanf("%s", str);
				printf("%d\n", query(root));
			}
			return 0;
		}

AC自动机
参考博客

题意第一行输入测试数据的组数,然后输入一个整数n,接下来的n行每行输入一个单词,最后输入一个字符串,问在这个字符串中有多少个单词出现过

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e7 + 5;
const int MAX = 10000000;
int cnt;
struct node{
    node *next[26];
    node *fail;
    int sum;
};
node *root;
char key[70];
node *q[MAX];
int head,tail;
node *newnode;
char pattern[maxn];
int N;
void Insert(char *s)
{
    node *p = root;
    for(int i = 0; s[i]; i++)
    {
        int x = s[i] - 'a';
        if(p->next[x] == NULL)
        {
            newnode=(struct node *)malloc(sizeof(struct node));
            for(int j=0;j<26;j++) newnode->next[j] = 0;
            newnode->sum = 0;newnode->fail = 0;
            p->next[x]=newnode;
        }
        p = p->next[x];
    }
    p->sum++;
}
void build_fail_pointer()
{
    head = 0;
    tail = 1;
    q[head] = root;
    node *p;
    node *temp;
    while(head < tail)
    {
        temp = q[head++];
        for(int i = 0; i <= 25; i++)
        {
            if(temp->next[i])
            {
                if(temp == root)
                {
                    temp->next[i]->fail = root;
                }
                else
                {
                    p = temp->fail;
                    while(p)
                    {
                        if(p->next[i])
                        {
                            temp->next[i]->fail = p->next[i];
                            break;
                        }
                        p = p->fail;
                    }
                    if(p == NULL) temp->next[i]->fail = root;
                }
                q[tail++] = temp->next[i];
            }
        }
    }
}
void ac_automation(char *ch)
{
    node *p = root;
    int len = strlen(ch);
    for(int i = 0; i < len; i++)
    {
        int x = ch[i] - 'a';
        while(!p->next[x] && p != root) p = p->fail;
        p = p->next[x];
        if(!p) p = root;
        node *temp = p;
        while(temp != root)
        {
           if(temp->sum >= 0)
           {
               cnt += temp->sum;
               temp->sum = -1;
           }
           else break;
           temp = temp->fail;
        }
    }
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        root=(struct node *)malloc(sizeof(struct node));
        for(int j=0;j<26;j++) root->next[j] = 0;
        root->fail = 0;
        root->sum = 0;
        scanf("%d",&N);
        getchar();
        for(int i = 1; i <= N; i++)
        {
            gets(key);
            Insert(key);
        }
        gets(pattern);
        cnt = 0;
        build_fail_pointer();
        ac_automation(pattern);
        printf("%d\n",cnt);
    }
    return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
AC自动机是一种高效的多模式匹配算法,可用于字符串匹配、关键词过滤等应用场景。PyHanLP是基于Java的HanLP的Python接口,提供了实现AC自动机的功能。 下面是使用PyHanLP实现基于双数组字典树AC自动机的示例代码: ```python from pyhanlp import * class ACAutomaton: def __init__(self): self.base = [] self.check = [] self.keyword_map = {} def build(self, keyword_list): keyword_map = {} for i, keyword in enumerate(keyword_list): keyword_map[keyword] = i self.keyword_map = keyword_map ac_automaton = JClass('com.hankcs.hanlp.algorithm.ahocorasick.trie.Trie')(keyword_map) ac_automaton.parseText(keyword_list) self.base = ac_automaton.getBase() self.check = ac_automaton.getCheck() def match(self, text): result = [] length = len(text) position = 1 for i in range(length): position = self._match_one_char(text, position) if position == -1: break if self.base[position] != 0: result.append((i - self.base[position] + 1, self.keyword_map[self._get_keyword(position)])) return result def _match_one_char(self, text, position): char = text[position - 1] base = self.base[position] next_position = base + char if position > 1 and self.check[next_position] != position - 1: return self._match_one_char(text, self.check[next_position]) if self.base[next_position] == -1: return -1 return next_position def _get_keyword(self, position): for keyword, index in self.keyword_map.items(): if index == position - self.base[position]: return keyword return None if __name__ == '__main__': keyword_list = ['abc', 'bcd', 'def', 'cde'] text = 'abcdef' ac_automaton = ACAutomaton() ac_automaton.build(keyword_list) result = ac_automaton.match(text) print(result) ``` 在代码中,首先定义了一个ACAutomaton类,用于实现AC自动机的匹配功能。在类的构造函数中,定义了三个成员变量:base、check和keyword_map。其中,base和check数组是AC自动机的核心数据结构,用于存储自动机的状态转移信息;keyword_map用于存储关键词和对应的索引。 在build方法中,利用HanLP提供的Trie类构建AC自动机,并将其转化为base和check数组,存储在对象的成员变量中。此外,还存储了关键词和索引的映射关系。 在match方法中,遍历文本的每个字符,利用base和check数组匹配关键词,并返回匹配结果。其中,每个匹配结果包含两个字段:匹配位置和匹配关键词的索引。 在_match_one_char方法中,实现AC自动机的状态转移过程。利用base和check数组以及文本的当前位置,计算下一个状态的位置,并判断是否存在匹配。如果存在匹配,则继续向后匹配;否则回溯到上一个状态,并继续匹配。 在_get_keyword方法中,根据状态的位置,查找关键词和索引的映射关系,并返回关键词。 最后,在main函数中,定义了一个关键词列表和一个文本字符串,并使用ACAutomaton类进行匹配。输出匹配结果。 使用PyHanLP实现基于双数组字典树AC自动机,可以实现高效的多模式匹配,适用于关键词过滤、敏感词检测等应用场景。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值