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")
    
  • 相关阅读:
    关于“平台”概念的解析
    学习新名词“MVP”(最简可行产品)
    Docker 部署Spring boot 项目如何优雅的关闭(Eureka下线)
    微服务健康监控方案
    Cpu飚高show-busy-java-threads一件脚本排查与Arthas线上诊断工具排查实战
    微服务发展规划(PS 大概分层未细化到具体系统)
    前后端分离研究
    Graphics2D画快递电子面单图片并且打印
    改写rm -rf 脚本
    检查系统信息脚本
  • 原文地址:https://www.cnblogs.com/LiCheng-/p/6593131.html
Copyright © 2011-2022 走看看