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")
原文地址:https://www.cnblogs.com/LiCheng-/p/6593131.html