Leetcode # 208 (Python): Implement Trie (Prefix Tree)

정욱·2021년 4월 21일
0

Leetcode

목록 보기
20/38
post-custom-banner

Implement Trie (Prefix Tree)

  • Difficulty: Medium
  • Type: Tree/Trie
  • link

Problem

Solution

  • Implement TrieNode first
  • Insert: continue to make the character the key for 'children'. When the word ends, make the word bool to True
  • Search: search until encountering the end of the word
import collections

class TrieNode:
    def __init__(self):
        self.word = False
        self.children = collections.defaultdict(TrieNode)

class Trie:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = TrieNode()

    def insert(self, word: str) -> None:
        """
        Inserts a word into the trie.
        """
        node = self.root
        for char in word:
            node = node.children[char]
        node.word = True

    def search(self, word: str) -> bool:
        """
        Returns if the word is in the trie.
        """
        node = self.root
        for char in word:
            if char not in node.children:
                return False
            node = node.children[char]
        return node.word

    def startsWith(self, prefix: str) -> bool:
        """
        Returns if there is any word in the trie that starts with the given prefix.
        """
        node = self.root
        for char in prefix:
            if char not in node.children:
                return False
            node = node.children[char]
        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)
post-custom-banner

0개의 댓글