Medium
首先需要获取Trie知识
m
是待插入/查询的字符串的长度。所以在一般的工程中,Trie见得比较少,应为要做测试才能比较Trie和Hash的效率。而且一般语言都有Hash的库,但是Trie对象要手撕
明显用Trie来做的题目的主要特征是,需要大量判断某个字符串是否是给定单词列表中的前缀或后缀
以上,尝试实现Trie
python3
class TrieNode:
def __init__(self):
self.children = {}
self.isWord = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for i in word:
if i not in node.children:
node.children[i] = TrieNode()
node = node.children[i]
node.isWord = True
def search(self, word: str) -> bool:
node = self.root
for i in word:
if i not in node.children:
return False
node = node.children[i]
return node.isWord
def startsWith(self, prefix: str) -> bool:
node = self.root
for p in prefix:
if p not in node.children:
return False
node = node.children[p]
return True