实现前缀树的插入,搜索和开头搜索三个功能
实现前缀树
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.lookup = {}
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
tree = self.lookup
for a in word:
if a not in tree:
tree[a] = {}#由于是不断遍历节点,所以a在tree的时候,就不需要变成下一个节点,想想树的结构不断分支
tree = tree[a]#和下面的题不一样的地方在于这个是不断变成下一个节点,所以最终tree={};而212题的tree是不断扩张的,最后是个{'a': {'a': {'b': {'c': {'end': 1}}}}, 'w': {'e': {'o': {'end': 1}}}}这种形式;
# 单词结束标志
tree["#"] = "#"
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
tree = self.lookup
for a in word:
if a not in tree:
return False
tree = tree[a]
if "#" in tree:
return True
return False
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
tree = self.lookup
for a in prefix:
if a not in tree:
return False
tree = tree[a]
return True
单词搜索Ⅱ 前缀树+DFS
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
trie = {}
for word in words:
t = trie
for w in word:
t = t.setdefault(w, {})
t["end"] = 1 #构建trie树的过程,形式类似这样,{'a': {'a': {'b': {'c': {'end': 1}}}}, 'w': {'e': {'o': {'end': 1}}}}
#print(trie)
res = []
row = len(board)
col = len(board[0])
def dfs(i, j, trie, s):
#print(i, j, trie, s)
c = board[i][j]
if c not in trie: return
trie = trie[c]
if "end" in trie and trie["end"] == 1:
res.append(s + c)
trie["end"] = 0 # 防止重复数组加入
board[i][j] = "#"
for x, y in [[-1, 0], [1, 0], [0, 1], [0, -1]]:
tmp_i = x + i
tmp_j = y + j
if 0 <= tmp_i < row and 0 <= tmp_j < col and board[tmp_i][tmp_j] != "#":
dfs(tmp_i, tmp_j, trie, s + c)
board[i][j] = c
for i in range(row):
for j in range(col):
dfs(i, j, trie, "")
return res