python版本
class Trie:
def __init__(self):
self.children={
}
def insert(self, word: str) -> None:
cur=self.children
for i in range(len(word)):
if word[i] not in cur.keys():
cur[word[i]]={
}
cur=cur[word[i]]
cur["end"]=True
def search(self, word: str) -> bool:
cur=self.children
for i in range(len(word)):
if word[i] not in cur.keys():
return False
cur=cur[word[i]]
return True if "end" in cur else False
def startsWith(self, prefix: str) -> bool:
cur=self.children
for i in range(len(prefix)):
if prefix[i] not in cur.keys():
return False
cur=cur[prefix[i]]
return True