LeetCode 208. Implement Trie (Prefix Tree)

题目描述:实现Trie树的查找、查找前缀、插入等操作。

题目链接:LeetCode 208. Implement Trie (Prefix Tree)

代码如下:

class Trie:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = {}
        self.is_end = -1

    def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: void
        """
        n = self.root
        for c in word:
            if n.get(c) is None:
                n[c] = {}
            n = n[c]
        n[self.is_end] = True
        

    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """
        n = self.root
        for c in word:
            if n.get(c) is None:
                return False
            n = n[c]
        return True if n.get(self.is_end) else False
        

    def startsWith(self, prefix):
        """
        Returns if there is any word in the trie that starts with the given prefix.
        :type prefix: str
        :rtype: bool
        """
        n = self.root
        for c in prefix:
            if n.get(c) is None:
                return False
            n = n[c]
        return True


参考链接

Trie
python 实现 trie(字典) 树

优缺点分析
打印结果

你可能感兴趣的:(LeetCode,二叉树)