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")
    
  • 相关阅读:
    windows计数器和瓶颈
    SQL Server 2005的Resource数据库
    Android学习笔记 json数据的解析
    android的消息处理机制(图+源码分析)——Looper,Handler,Message
    JS刷新验证码
    Java取得Unix的timestamp
    (转载)DBMS_SQL package 学习
    关于Java中Http下载的一些整理
    (转载)sqlserver内存释放
    关于EL表达式
  • 原文地址:https://www.cnblogs.com/LiCheng-/p/6593131.html
Copyright © 2011-2022 走看看