class TrieNode:
def __init__(self):
self.children = {}#self.children = collections.defaultdict(TrieNode)
self.isEnd = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
""" tc O(W) sc O(W) W: length of word
"""
cur = self.root
for c in word:
if c not in cur.children:
cur.children[c] = TrieNode()
cur = cur.children[c]
cur.isEnd = True
def search(self, word: str) -> bool:
""" tc O(W) sc O(1) W: length of word
"""
cur = self.root
for c in word:
if c not in cur.children:
return False
cur = cur.children[c]
return cur.isEnd
def search(self, word: str) -> bool:
"""tc O(W) sc O(1) W: length of word
"""
cur = self.root
for c in word:
if c not in cur.children:
return False
cur = cur.children[c]
return cur.isEnd
def startsWith(self, prefix: str) -> bool:
""" tc O(P) sc O(1) P: length of prefix
"""
cur = self.root
for c in prefix:
if c not in cur.children:
return False
cur = cur.children[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)