Implement Trie (Prefix Tree)

Implement a trie with insert, search, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.

终于进军trie树,trie树也称子典树或者前缀树(prefix tree). 因为trie树是一个字母一个字母存储,避免单词存储的极大空间浪费.每次查找字符的时间复杂度为O(len(word)). 注意一点是trie的每个节点需要标志是不是一个单词的结尾.

trie既可以用数组实现,也可以用hashmap实现,数组实现则对每个节点都需要开一个26维数组('a'-'z'小写字母的情况下),不单纯是小写字母的情况则可能还要复杂.用hashmap是节省空间且便捷的措施.

代码如下:

class TrieNode(object):
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.children = {}
        self.hasword = False
        

class Trie(object):

    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: void
        """
        node = self.root
        for i in word:
            if not node.children.get(i):
                node.children[i] = TrieNode()
            node = node.children[i]
        node.hasword = True
        
    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """
        node = self.root
        for i in word:
            if not node.children.get(i):
                return False
            node = node.children[i]
        return node.hasword

    def startsWith(self, prefix):
        """
        Returns if there is any word in the trie
        that starts with the given prefix.
        :type prefix: str
        :rtype: bool
        """
        node = self.root
        for i in prefix:
            if not node.children.get(i):
                return False
            node = node.children[i]
        return True
        

注意search是要判读这个单词是否在字典中的,查找前缀不需要~

转载于:https://www.cnblogs.com/sherylwang/p/5639617.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值