[LeetCode]Implement Trie (Prefix Tree)

题目描述:

Implement a trie with insert, search, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.

题目大意:

实现字典树,包含插入,查找和前缀查找方法。

注意:

你可以假设所有的输入只包含小写字母a-z

解题思路:

本题考查字典树数据结构的基础知识。

Trie使用孩子表示法存储,TrieNode为字典树的节点,包含属性childs和isWord。

其中childs为dict,存储当前节点的后代节点;isWord为布尔值,表示当前节点是否存储了一个单词。

Python代码:

class TrieNode:
    # Initialize your data structure here.
    def __init__(self):
        self.children = dict()
        self.isWord = False

class Trie:

    def __init__(self):
        self.root = TrieNode()

    # @param {string} word
    # @return {void}
    # Inserts a word into the trie.
    def insert(self, word):
        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

    # @param {string} word
    # @return {boolean}
    # Returns if the word is in the trie.
    def search(self, word):
        node = self.root
        for letter in word:
            node = node.children.get(letter)
            if node is None:
                return False
        return node.isWord

    # @param {string} prefix
    # @return {boolean}
    # Returns if there is any word in the trie
    # that starts with the given prefix.
    def startsWith(self, prefix):
        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")

 

本文链接:http://bookshadow.com/weblog/2015/05/08/leetcode-implement-trie-prefix-tree/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论