解题思路:
利用链表的思路去解决问题,不过不同于正常的链表节点的指针部分,这里可能有0到26个节点。
具体实现的代码如下:
class Node:
def __init__(self):
self.next = {}
self.tag = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.trie = Node()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
node = self.trie
for i in range(len(word)):
if word[i] not in node.next:
node.next[word[i]] = Node()
node = node.next[word[i]]
node.tag = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
node = self.trie
for char in word:
if char not in node.next:
return False
node = node.next[char]
return node.tag
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
node = self.trie
for char in prefix:
if char not in node.next:
return False
node = node.next[char]
return True