[英]Trie tree match performance in word search
我調試了一些類似的解決方案,但想知道我們是否可以將 Trie Tree 改進為部分匹配前綴(在類 Trie 的搜索方法中,當前搜索方法僅檢查是否匹配完整單詞)甚至提高性能,這可能會返回之前走錯了路? 我對這個想法不是很有信心,所以請盡早尋求建議。
我發布了一個類似的解決方案。 謝謝。
給定一個 2D 板和字典中的單詞列表,找到板中的所有單詞。
每個單詞必須由順序相鄰單元格的字母構成,其中“相鄰”單元格是水平或垂直相鄰的單元格。 同一個字母單元格不能在一個單詞中多次使用。
例如, Given words = ["oath","pea","eat","rain"]
和 board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
返回 ["吃","誓言"]
class TrieNode():
def __init__(self):
self.children = collections.defaultdict(TrieNode)
self.isWord = False
class Trie():
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for w in word:
node = node.children[w]
node.isWord = True
def search(self, word):
node = self.root
for w in word:
node = node.children.get(w)
if not node:
return False
return node.isWord
class Solution(object):
def findWords(self, board, words):
res = []
trie = Trie()
node = trie.root
for w in words:
trie.insert(w)
for i in xrange(len(board)):
for j in xrange(len(board[0])):
self.dfs(board, node, i, j, "", res)
return res
def dfs(self, board, node, i, j, path, res):
if node.isWord:
res.append(path)
node.isWord = False
if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]):
return
tmp = board[i][j]
node = node.children.get(tmp)
if not node:
return
board[i][j] = "#"
self.dfs(board, node, i+1, j, path+tmp, res)
self.dfs(board, node, i-1, j, path+tmp, res)
self.dfs(board, node, i, j-1, path+tmp, res)
self.dfs(board, node, i, j+1, path+tmp, res)
board[i][j] = tmp
我看不出你代碼中的Trie
部分有什么問題。
但是我認為在檢測到任何不匹配時,trie 的原始設計已經提前返回。
實際上,我通常只使用常規dict
作為 trie 而不是defaultDict + TrieNode
以避免使問題過於復雜。 如果某個節點是有效單詞,您只需要設置一個"#"
鍵。 並且,在插入期間,只需執行node[w] = {}
。
如果您這樣做,您的代碼可以顯着簡化並且提前返回將很簡單,因為您在節點中根本不會有“錯誤”的鍵!
例如,一個只包含'ab'
的簡單樹看起來像: {'a': {'b': {'#': {}}}
。 因此,當您搜索'cd'
,一旦您意識到最外層的 dict 中沒有鍵'c'
,您就可以返回 false。 這個實現與你的類似,但我相信它更容易理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.