Implement Trie (Prefix Tree)

leetcode第208题,字典树的简单实现,上次数学建模比赛的时候就是用的字典树,对于这种数据结构的原理还是比较了解的,不过当时编程水平堪忧,调试了很久。这次我用python来实现字典树,为了实现后缀,我采用字典,这样可以随着动态绑定,另外字典树最重要的还要加入停止标记,来确保单词在什么位置结束。

实现的时候注意几个细节:

1、插入操作时,如果没有达到单词结尾,则正常加挂节点,同时节点向下传递,如果达到了单词结尾,则要在节点上加入停止标记。每种大情况还分两种小情况,一种是该字母已经在children存在了,只需要标记或者向下传递即可。如果该字母还没有,则需要创建新的子节点加挂上去再做上述操作。

2、查找操作的时候,如果字母在children根本不存在,则说明字母不对应,立刻返回False。向下查找时如果单词结束且遇到了单词停止标记,则说明查找成功。如果单词结束了还没有遇到停止标记,查找失败。

3、实现startwith和search非常相似,不同的是,即使这里单词结束了,但是没有停止标记,也允许返回True。

class TrieNode(object):
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.val = None
        self.end = False
        self.childern = {}

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
        n = len(word)
        for index,c in enumerate(word):
            if index == n-1:
                if c not in node.childern:
                    newNode = TrieNode()
                    newNode.end = True
                    node.childern[c] = newNode
                else:
                    node.childern[c].end = True
            else:
                if c not in node.childern:
                    newNode = TrieNode()
                    node.childern[c] = newNode
                    node = newNode
                else:
                    node = node.childern[c]


    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """
        node = self.root
        n = len(word)
        for index,c in enumerate(word):
            if c in node.childern:
                if node.childern[c].end == True and index == n-1:
                    return True
                else:
                    if index == n-1:
                        return False
                    else:
                        node = node.childern[c]
            else:
                return False

    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
        n = len(prefix)
        for index,c in enumerate(prefix):
             if c in node.childern:
                if node.childern[c].end == True and index == n-1:
                    return True
                else:
                    node = node.childern[c]
             else:
                return False
        return True


# Your Trie object will be instantiated and called as such:
trie = Trie()
trie.insert("somestring")
trie.insert("key")
print trie.search("key")
print trie.search("somestring")
print trie.startsWith("as")


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值