8/29/2020

[LeetCode] 208. Implement Trie (Prefix Tree)

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

One node of Trie represents a letter of the inserted words.

To search an inserted word, the code travels from the root node and find if current letter is represented by one of the child node.  When reach to the last letter of the given word, check if  Node.end = True.


class Node:
    def __init__(self, val = '', end = False):
        self.val = val
        self.end = end
        self.nxt = {}

class Trie:

    def __init__(self):
        self.root = Node()
        
    def insert(self, word: str) -> None:
        p = self.root
        
        for w in word:
            if w not in p.nxt:
                p.nxt[w] = Node(w)
            
            p = p.nxt[w]
        
        p.end = True
                
    def search(self, word: str) -> bool:
        p = self.root
        
        for w in word:
            if w not in p.nxt:
                return False
            p = p.nxt[w]
        
        return p.end

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

Edited on 10/08/2021. Tidy the implementation.

No comments:

Post a Comment