Trie:字符串匹配剪枝
Autocomplete & Autocorrection
def getWords(swipes, trie):
def helper(i, root, word):
if i==len(swipes): return
if root.isWord:
res.append(word)
return
ch = swipes[i]
if ch in root.children:
helper(i+1, root.children[ch], word+ch)
helper(i+1, root, word)
res = []
helper(0, trie.root, "")
return res
words = ["apple", "boba", "tea", "car"]
swipe = "bnhjkiocikjhanbvcxszarm"
getWords(swipe, Trie(words)) == {'boba', 'car'}
# 回溯写法
def getWords(swipes, trie):
def helper(i, path, word):
if i==len(swipes): return
if path[-1].isWord:
res.append(word)
return
ch = swipes[i]
if ch in path[-1].children:
path.append(path[-1].children[ch])
helper(i+1, path, word+ch)
path.pop()
return
res = []
helper(0, [trie.root], "")
return res前缀树

Dict简单实现
例题:最大异或值
Last updated