208. Implement Trie (Prefix Tree)
My solution:
python
class Node:
__slots__ = 'son', 'end'
def __init__(self):
self.son = {}
self.end = False
class Trie:
def __init__(self):
self.root = Node()
def insert(self, word: str) -> None:
cur = self.root
for c in word:
if c not in cur.son:
cur.son[c] = Node()
cur = cur.son[c]
cur.end = True
def search(self, word: str) -> bool:
cur = self.root
for c in word:
if c not in cur.son:
return False
cur = cur.son[c]
return True if cur.end else False
def startsWith(self, prefix: str) -> bool:
cur = self.root
for c in prefix:
if c not in cur.son:
return False
cur = cur.son[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)
Solution with comments:
python
class Node:
__slots__ = 'son', 'end'
def __init__(self):
self.son = {}
self.end = False
class Trie:
def __init__(self):
self.root = Node()
def insert(self, word: str) -> None:
cur = self.root
for c in word:
if c not in cur.son: # 无路可走?
cur.son[c] = Node() # 那就造路!
cur = cur.son[c]
cur.end = True
def find(self, word: str) -> int:
cur = self.root
for c in word:
if c not in cur.son: # 道不同,不相为谋
return 0
cur = cur.son[c]
# 走过同样的路(2=完全匹配,1=前缀匹配)
return 2 if cur.end else 1
def search(self, word: str) -> bool:
return self.find(word) == 2
def startsWith(self, prefix: str) -> bool:
return self.find(prefix) != 0
作者:灵茶山艾府
链接:https://leetcode.cn/problems/implement-trie-prefix-tree/solutions/2993894/cong-er-cha-shu-dao-er-shi-liu-cha-shu-p-xsj4/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
边表示字符,点表示是否结束