字典树

本想了解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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值