字典树

初次接触字典树,什么是字典树呢?

字典树又被称为是前缀树。

https://blog.csdn.net/weixin_39778570/article/details/81990417博客里,

从上图归纳出Trie树基本性质.

  1. 从根到某一个节点,拼接长字符串;
  2. 一个节点的子节点字符一定不相同;
  3. Trie提高效率,用空间换时间

数据结构常见的操作是:插入、查找、删除

对于字典树来说,删除我还不会。

插入字符串时,逐个字符对比,在python中用字典来保存节点,而且每个字符串都要有结束标记,如biac {"b":{"i":{"a":{"c:{"#":"#"}"}}}}。

查找字符串时,逐个字符对比,最后如果有结束标记,那么返回True,如果没有返回False。

代码如下:

class Trie:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.lookup = {}
        

    def insert(self, word: str) -> None:
        """
        Inserts a word into the trie.
        """
        tree = self.lookup
        for a in word:
            if a not in tree:
                tree[a] = {} #不断的在字典中添加节点,新节点都是以字典的形式内嵌进大字典的
            tree = tree[a] #不断内嵌
            # print(tree)
        # 单词结束标志
        tree["#"] = "#"
        # print(self.lookup) #{'b': {'i': {'a': {'c': {'#': '#'}}}}}
        

    def search(self, word: str) -> bool:
        """
        Returns if the word is in the trie.
        """
        tree = self.lookup
        for a in word:
            if a not in tree:
                return False
            tree = tree[a]
        if "#" in tree:
            return True
        return False
        

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

代码源于:https://leetcode-cn.com/problems/implement-trie-prefix-tree/solution/pythonjian-dan-shi-xian-by-powcai/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值