本想了解AC自动机
先掌握trie树
思想来自 浅谈Trie树(字典树)感谢
# trie树
class TrIe(object):
def __init__(self):
self.ise = [False for i in range(40000)] # is end? 记录是否为单词结尾
self.sum = [0 for i in range(40000)] # how many times the prefix is used 记录前缀出现多少次
self.trie = [[-1 for i in range(26)] for j in range(40000)] # 构件trie树
self.node_num = -1 # 全局变量,记录节点的号
def insert(self, word):
root = 0
len_of_word = len(word)
for i in range(len_of_word):
child_idx = ord(word[i]) - ord('a')
if self.trie[root][child_idx] == -1:
self.node_num += 1
self.trie[root][child_idx] = self.node_num
root = self.node_num
self.ise[root] = True
self.sum[root] += 1
def find(self, word):
root = 0
len_of_word = len(word)
for i in range(len_of_word):
child_idx = ord(word[i]) - ord('a')
if self.trie[root][child_idx] == -1:
return False
root = self.trie[root][child_idx]
return self.ise[root], self.sum[root]
exam = TrIe()
insert_lst = ["apple", "pig", "reputation", "never"]
for i in insert_lst:
exam.insert(i)
print(exam.find("apple"))
->(True, 1)