https://leetcode.com/problems/implement-trie-prefix-tree/

 

Implement Trie (Prefix Tree) - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

그냥 트라이를 알고있냐 모르고있냐를 보는거같다.

그렇게 어렵지 않다. 트라이가 뭔지 알고 구현을 한번이라도 해봤으면 금방 푸는 문제.

 

class Node:
    def __init__(self):
        self.next = {}
        self.isWord = False

class Trie:

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

    def insert(self, word: str) -> None:
        node = self.root
        
        for ch in word:
            if ch not in node.next:
                node.next[ch] = Node()
            node = node.next[ch]
        
        node.isWord = True

    def search(self, word: str) -> bool:
        node = self.root
        
        for ch in word:
            if ch not in node.next:
                return False
            node = node.next[ch]
        
        return node.isWord

    def startsWith(self, prefix: str) -> bool:
        node = self.root
        
        for ch in prefix:
            if ch not in node.next:
                return False
            node = node.next[ch]
            
        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)

+ Recent posts