前缀树(字典树)

前缀树可以用来解决诸如搜索提示,字符串查询等问题,实现一个前缀树首先需要定义一个前缀树结点,结点不代表字符串中的字符,每个结点的值通常有end(表示是否是某个字符串结尾),past(表示有多少单词经过此结点),next_node(是一个字典,其中key代表此结点相连的字符,value代表这条字符所代表的边连接的结点)。

定义前缀树类时,首先要初始化一个前缀树结点,然后定义常用的方法,如插入,删除,搜索和startwith,其基本搜索过程类似,以插入举例,首先定义一个变量node指向root,然后循环遍历字符串,若next_node[当前遍历字符]为空,说明没有当前字符的边,我们直接将这个key加入哈希表,下一步将node更新至next_node[当前遍历字符],当遍历完成后,说明遍历到了字符串末尾,定义node.end = True(若想下次查询获取加入次数,则这里应当定义为数字)

class Trienode:
    def __init__(self):
        self.end = False
        self.next_node = {}

class Trie:
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = Trienode()
        


    def insert(self, word: str) -> None:
        """
        Inserts a word into the trie.
        """
        if not word:
            return
        node = self.root
        for w in word:
            if w not in node.next_node:
                node.next_node[w] = Trienode()
            node = node.next_node[w]
        node.end = True            

    def search(self, word: str) -> bool:
        """
        Returns if the word is in the trie.
        """
        if not word:
            return False
        node = self.root
        for w in word:
            if w not in node.next_node:
                return False
            node = node.next_node[w]
        return node.end

    def startsWith(self, prefix: str) -> bool:
        """
        Returns if there is any word in the trie that starts with the given prefix.
        """
        node = self.root
        for w in prefix:
            if w not in node.next_node:
                return False
            node = node.next_node[w]
        return True

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值