[英]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.