Skip to content

Latest commit

 

History

History
73 lines (51 loc) · 1.54 KB

_208. Implement Trie (Prefix Tree).md

File metadata and controls

73 lines (51 loc) · 1.54 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 27, 2024

Last updated : June 27, 2024


Related Topics : Hash Table, String, Design, Trie

Acceptance Rate : 65.465 %


Solutions

Python

class Trie:

    def __init__(self):
        self.trie = {}

    def insert(self, word: str) -> None:
        curr = self.trie

        for c in word :
            if c in curr :
                curr = curr[c]
            else :
                curr[c] = {}
                curr = curr[c]

        curr['#'] = True

    def search(self, word: str) -> bool:
        curr = self.trie
        for c in word :
            if c not in curr :
                return False
            curr = curr[c]

        if '#' in curr :
            return True
        
        return False

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