Leetcode212. Word Search II
Leetcode212. Word Search II
题目
思路
将词典构建为Trie,
对board中的每个字母,进行dfs遍历,检查是否在Trie中
复杂度
设词典最长词的长度为L,board有M行N列
-
时间复杂度 O ( n ) \mathcal{O}(n) O(n)
最坏情况,board中的每个字母,向四个方向都能不停的匹配下去,直到达到字典中的单词长度,如字典为aaaaaa,board中字母也全是a,则时间复杂度为 O ( 4 ∗ L ∗ M ∗ N ) = O ( L ∗ M ∗ N ) \mathcal{O}(4*L*M*N)=\mathcal{O}(L*M*N) O(4∗L∗M∗N)=O(L∗M∗N)
最好情况,board中的每个字母,在Trie中都没有匹配到起点, O ( M ∗ N ) \mathcal{O}(M*N) O(M∗N) -
空间复杂度 O ( n ) \mathcal{O}(n) O(n)
board占用 O ( M ∗ N ) \mathcal{O}(M*N) O(M∗N)
Trie:
最坏情况,所有单词前缀都相同,如[a, ab, abc, abcd],则占用的空间为最长单词的长度, O ( L ) \mathcal{O}(L) O(L)
最好情况,所有单词没有共用的前缀,如[a, bc, cde, defg],则占用空间为所有单词的长度之和, ∑ i = 0 l e n ( w o r d s ) O ( l e n ( w o r d s [ i ] ) ) \sum_{i=0}^{len(words)} \mathcal{O}(len(words[i])) ∑i=0len(words)O(len(words[i])),应该在 O ( L 2 ) \mathcal{O}(L^2) O(L2)量级
代码
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
if not board or not words:
return []
m = len(board)
n = len(board[0])
# 建立trie
trie = {}
for w in words:
temp = trie
for c in w:
if c not in temp:
temp[c] = {}
temp = temp[c]
# 末尾标记
temp['\n'] = w
def search(trie,i,j):
c = board[i][j]
temp = trie[c]
board[i][j] = '' # 防止从o访问到a后,又回头访问o
if '\n' in temp: # 在trie中匹配到了完整的单词
self.ans.append(temp.pop('\n'))
# 向四个方向搜索
if i > 0 and board[i-1][j] in temp:
search(temp,i-1,j)
if j > 0 and board[i][j-1] in temp:
search(temp,i,j-1)
if i < m-1 and board[i+1][j] in temp:
search(temp,i+1,j)
if j < n-1 and board[i][j+1] in temp:
search(temp, i, j+1)
board[i][j] = c
self.ans = []
for i in range(m):
for j in range(n):
# 在trie中的才进行搜索
if board[i][j] in trie:
search(trie, i, j)
return self.ans