208. Implement Trie (Prefix Tree)

class Trie:   
    class Node:
        def __init__(self):
            self.children = {}
            self.isEnd = False

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

    def insert(self, word: str):
        p = self.root
       
        for ch in word:
            if ch not in p.children:
                p.children[ch] = Trie.Node()
            p = p.children[ch]
        p.isEnd = True

    def search(self, word: str):
        p = self.root
       
        for ch in word:
            if ch not in p.children:
                return False
            p = p.children[ch]
        return p.isEnd

    def startsWith(self, prefix: str):
        p = self.root
        for ch in prefix:
            if ch not in p.children:
                return False
            p = p.children[ch]
        return True

Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break