zoukankan      html  css  js  c++  java
  • LeetCode 208 : Implement Trie (Prefix Tree)

    原题

    Implement a trie with insertsearch, and startsWith methods.

    实现一个 Trie,包含 insert, search, 和 startsWith 这三个方法。

    样例

    insert("lintcode")
    search("code") # return false
    startsWith("lint") # return true
    startsWith("linterror") # return false
    insert("linterror")
    search("lintcode) # return true
    startsWith("linterror") # return true
    

    解题思路

    • 首先,定义一个trie树节点,包含当前的char和isWord布尔值
    • 注意根节点不包含字符,每个节点最多有26叉
    • Insert - 即遍历单词的每个字符,逐层查找,有则继续,没有就创建一个新的TrieNode,最后一位IsWord = True
    • Search - 同理,遍历单词每个字符,逐层查找,没有立即返回False,找到最后一个TrieNode,则返回 TrieNode.IsWord
    • StartsWith - 同理,遍历单词每个字符,逐层查找,没有立即返回False,找到最后一个TrieNode,则直接返回 True

    完整代码

    class TrieNode(object):
        def __init__(self):
            """
            Initialize your data structure here.
            """
            self.children = {}
            self.IsWord = 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 letter in word:
                child = node.children.get(letter)
                if child is None:
                    child = TrieNode()
                    node.children[letter] = child
                node = child
            node.IsWord = True
    
        def search(self, word):
            """
            Returns if the word is in the trie.
            :type word: str
            :rtype: bool
            """
            node = self.root
            for letter in word:
                node = node.children.get(letter)
                if node is None:
                    return False
            return node.IsWord
    
        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 letter in prefix:
                node = node.children.get(letter)
                if node is None:
                    return False
            return True
    
    # Your Trie object will be instantiated and called as such:
    # trie = Trie()
    # trie.insert("somestring")
    # trie.search("key")
    
  • 相关阅读:
    restic 快速安全可靠的数据备份工具
    使用sidekick 负载均衡minio 集群
    sidekick简单试用
    使用nfpm打包deb&&rpm
    sidekick minio 团队开源的高性能http sidecar 负载均衡器
    baretest小巧但是强大的jest可选测试框架
    fetchq-cron 基于webhook 的任务调度工具
    uwsgi+nginx+flask+docker+supervisord oracle中文乱码问题
    gqless 一个强大灵活的不用写query的graphql client
    cortex 1.0 版本发布
  • 原文地址:https://www.cnblogs.com/LiCheng-/p/6593131.html
Copyright © 2011-2022 走看看