0208. Implement Trie (Prefix Tree)
Medium | Design + String | 112 ms (99.40%), 29.6 MB (93.89%)
Input:
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output:
[null, null, true, false, true, null, true]
Explanation
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // return True
trie.search("app"); // return False
trie.startsWith("app"); // return True
trie.insert("app");
trie.search("app"); // return Trueclass Trie:
def __init__(self):
self.root = {}
def insert(self, word: str) -> None:
# time : O(n), n is the lenght of str
# space : O(n)
cur = self.root
for char in word:
if char not in cur: cur[char] = {}
cur = cur[char]
cur['#'] = True
def search(self, word: str) -> bool:
# time : O(n)
# space : O(1)
cur = self.root
for char in word:
if char not in cur: return False
cur = cur[char]
return '#' in cur
def startsWith(self, prefix: str) -> bool:
# time : O(n)
# space : O(1)
cur = self.root
for char in prefix:
if char not in cur: return False
cur = cur[char]
return True
Last updated