设计一个支持以下两种操作的数据结构:
void addWord(word)
bool search(word)
search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 .
或 a-z
。 .
可以表示任何一个字母。
示例:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
说明:
你可以假设所有单词都是由小写字母 a-z
组成的。
解题思路
由于这是一个字符串检索的问题,并且有了之前问题的基础 Leetcode 208:实现 Trie (前缀树)(超详细解决方案!!!),所以我们这里不难想到建立一个Trie
结构,然后对于.
的模糊匹配,通过dfs
或者bfs
即可解决。首先使用bfs
class Node:
def __init__(self, isWord=False):
self.isWord = isWord
self.next = dict()
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = Node()
def addWord(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: void
"""
cur = self.root
for c in word:
if c not in cur.next:
cur.next[c] = Node()
cur = cur.next[c]
if not cur.isWord:
cur.isWord = True
def search(self, word):
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool
"""
stack = [(self.root, word)]
while stack:
node, w = stack.pop()
if not w:
if node.isWord:
return True
elif w[0] == '.':
for c in node.next.values():
stack.append([c, w[1:]])
elif w[0] in node.next:
stack.append([node.next[w[0]], w[1:]])
return False
迭代版本的dfs
,我们只需要将stack
换成queue
即可。在python
中,我们只需要通过pop(0)
即可。
def search(self, word):
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool
"""
stack = [(self.root, word)]
i, word_len = 0, len(word)
while stack:
node, w = stack.pop(0)
if not w:
if node.isWord:
return True
elif w[0] == '.':
for c in node.next.values():
stack.append([c, w[1:]])
elif w[0] in node.next:
stack.append([node.next[w[0]], w[1:]])
return False
dfs
的递归写法。
def search(self, word):
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool
"""
return self.dfs(self.root, word)
def dfs(self, node, word):
if not word:
return node.isWord
if word[0] not in node.next:
if word[0] == '.':
for c in node.next.values():
if self.dfs(c, word[1:]):
return True
return False
else:
return self.dfs(node.next[word[0]], word[1:])
上面的写法中用了一些trick
,大家可以仔细看看。这个问题最快的解法不是用Trie
这个结构,而是通过字典。我们通过字典记录相同长度的单词,然后查询的时候根据单词的长度进行查询,对于包含.
的单词,我们枚举所有长度一致的单词然后判断是不是存在。
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = collections.defaultdict(list)
def addWord(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: void
"""
self.root[len(word)].append(word)
def search(self, word):
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool
"""
if not word:
return False
if "." not in word:
return word in self.root[len(word)]
for v in self.root[len(word)]:
for i, s in enumerate(word):
if s != v[i] and s != ".":
break
else:
return True
return False
虽然上述解法的速度很快,但是认为这不是一个优秀的解法。在python
中一个建立Trie
的技巧
from collections import defaultdict
def _trie():
return defaultdict(_trie)
reference:
我将该问题的其他语言版本添加到了我的GitHub Leetcode
如有问题,希望大家指出!!!