Created
July 17, 2020 09:09
-
-
Save Youngestdev/f127c91064d35d34c96cb99fb8ef2531 to your computer and use it in GitHub Desktop.
Implemented a Trie ( Preffix tree )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Trie: | |
def __init__(self): | |
""" | |
Initialize your data structure here. | |
""" | |
self.root = {} | |
def insert(self, word: str) -> None: | |
""" | |
Inserts a word into the trie. | |
""" | |
cur = self.root | |
for char in word: | |
cur = cur.setdefault(char, {}) | |
cur["#"] = True | |
def search(self, word: str) -> bool: | |
""" | |
Returns if the word is in the trie. | |
""" | |
cur = self.root | |
for char in word: | |
if char not in cur: return False | |
cur = cur[char] | |
return cur.get("#", False) | |
def startsWith(self, prefix: str) -> bool: | |
""" | |
Returns if there is any word in the trie that starts with the given prefix. | |
""" | |
cur = self.root | |
for char in prefix: | |
if char not in cur: return False | |
cur = cur[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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment