class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.data = {}
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
d = self.data
for w in word:
if w not in d:
d[w] = {}
d = d[w]
d["#"] = '#'
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
return self.startsWith(word+"#")
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
d = self.data
for w in prefix:
if w not in d:
return False
else:
d = d[w]
return True
Runtime: 112 ms, faster than 99.90% of Python3 online submissions for Implement Trie (Prefix Tree).
Memory Usage: 26.1 MB, less than 66.67% of Python3 online submissions for Implement Trie (Prefix Tree).
用node
class TrieNode:
def __init__(self):
from collections import defaultdict
self.children = defaultdict(TrieNode)
self.isEnd = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
node = self.root
for w in word:
node = node.children[w]
node.isEnd = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
node = self.root
for w in word:
node = node.children.get(w)
if node is None:
return False
return node.isEnd
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
node = self.root
for w in prefix:
node = node.children.get(w)
if node is None:
return False
return True
Runtime: 216 ms, faster than 32.09% of Python3 online submissions for Implement Trie (Prefix Tree).
Memory Usage: 31.5 MB, less than 7.41% of Python3 online submissions for Implement Trie (Prefix Tree).