LeetCode 208. [Python] Implement Trie (Prefix Tree)
原题链接
中等
作者:
徐辰潇
,
2021-02-18 05:59:26
,
所有人可见
,
阅读 409
class Node:
#Define a new structure
def __init__(self):
self.children = {} #key:char #val: tree Node
self.isEnd = False
class Trie:
#TC: O(l) where l is length of word/prefix for insert, search and startsWith
#SC: max O(nl) where n is total number of words instored
def __init__(self):
"""
Initialize your data structure here.
"""
self.dummy = Node()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
head = self.dummy
for idx, char in enumerate(word):
if char not in head.children:
head.children[char] = Node()
head = head.children[char]
if idx == len(word)-1:
head.isEnd = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
head = self.dummy
for idx, char in enumerate(word):
if char not in head.children:
return False
head = head.children[char]
if idx == len(word) - 1:
return head.isEnd
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
head = self.dummy
for idx, char in enumerate(prefix):
if char not in head.children:
return False
head = head.children[char]
if idx == len(prefix) - 1:
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)