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")
    
  • 相关阅读:
    移动端底部fixed固定定位输入框ios下不兼容
    mint-ui Picker设置指定初始值
    vue项目的mode:history模式
    更改checkbox的默认样式
    vue组件通信的几种方式
    Python运行Google App Engineer时出现的UnicodeDecodeError错误解决方案
    ActionFilterAttribute之HtmlFilter,压缩HTML代码
    MongoDB C#驱动中Query几个方法
    无需路由端口映射 花生壳6.5工程版发布
    如何让搜索引擎抓取AJAX内容?
  • 原文地址:https://www.cnblogs.com/LiCheng-/p/6593131.html
Copyright © 2011-2022 走看看