python leetcode 208. Implement Trie (Prefix Tree)

import collections
class Node(object):
    def __init__(self):
        self.children = collections.defaultdict(Node)
        self.isword = False
class Trie(object):
    
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = Node()
        
    def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: void
        """
        current = self.root 
        for w in word:
            current = current.children[w]
        current.isword = True

    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """
        current = self.root
        for w in word:
            current = current.children.get(w)
            if current == None:
                return False 
        return current.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
        """
        current = self.root 
        for w in prefix:
            current = current.children.get(w)
            if current == None:
                return False 
        return True

猜你喜欢

转载自blog.csdn.net/Neekity/article/details/85036534