leetcode 208. Implement Trie (Prefix Tree)

来源:互联网 发布:淘宝优惠卷群怎么代理 编辑:程序博客网 时间:2024/06/06 11:02
class TrieNode(object):    def __init__(self):        self.is_leaf = False        self.children = collections.defaultdict(TrieNode)class Trie(object):    """    https://discuss.leetcode.com/topic/14202/ac-python-solution    """    def __init__(self):        self.root = TrieNode()            def insert(self, word):        """        Inserts a word into the trie.        :type word: str        :rtype: void        """        cur = self.root        for letter in word:            cur = cur.children[letter]        cur.is_leaf = True    def search(self, word):        """        Returns if the word is in the trie.        :type word: str        :rtype: bool        """        cur = self.root        for letter in word:            cur = cur.children.get(letter)            if cur is None:                return False        return cur.is_leaf    def startsWith(self, prefix):        """        Returns if there is any word in the trie that starts with the given prefix.        :type prefix: str        :rtype: bool        """        cur = self.root        for letter in prefix:            cur = cur.children.get(letter)            if cur is None:                return False        return True# Your Trie object will be instantiated and called as such:# obj = Trie()# obj.insert(word)# param_2 = obj.search(word)# param_3 = obj.startsWith(prefix)

原创粉丝点击