题目-中等难度
请你设计一个数据结构,支持 添加新单词 和 查找字符串是否与任何先前添加的字符串匹配 。
实现词典类 WordDictionary :
- WordDictionary() 初始化词典对象
- void addWord(word) 将 word 添加到数据结构中,之后可以对它进行匹配
- bool search(word) 如果数据结构中存在字符串与 word 匹配,则返回 true ;否则,返回 false 。word 中可能包含一些 ‘.’ ,每个 . 都可以表示任何一个字母。
示例
示例:
输入:
[“WordDictionary”,“addWord”,“addWord”,“addWord”,“search”,“search”,“search”,“search”]
[[],[“bad”],[“dad”],[“mad”],[“pad”],[“bad”],[“.ad”],[“b…”]]
输出:
[null,null,null,null,false,true,true,true]
解释:
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord(“bad”);
wordDictionary.addWord(“dad”);
wordDictionary.addWord(“mad”);
wordDictionary.search(“pad”); // 返回 False
wordDictionary.search(“bad”); // 返回 True
wordDictionary.search(“.ad”); // 返回 True
wordDictionary.search(“b…”); // 返回 True
提示:
- 1 <= word.length <= 25
- addWord 中的 word 由小写英文字母组成
- search 中的 word 由 ‘.’ 或小写英文字母组成
- 最多调用 104 次 addWord 和 search
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/design-add-and-search-words-data-structure
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
1.
class TrieNode:
def __init__(self):
# 每个节点有26个可能的子节点, 对应26个英文字母
self.children = [None] * 26
# 标记这个节点是否是当前单词的最后一个字母
self.isLast = False
class WordDictionary:
def __init__(self):
# 初始化时创建根节点
self.li = TrieNode()
def addWord(self, word: str) -> None:
# 从根节点开始
node = self.li
# 遍历单词中的每个字母
for w in word:
# 计算字母对应的索引
c = ord(w) - ord('a')
# 如果相应的子节点不存在
if not node.children[c]:
# 创建新的子节点
node.children[c] = TrieNode()
# 移动到子节点, 继续处理下一个字母
node = node.children[c]
# 标记单词的最后一个字母
node.isLast = True
def search(self, word: str) -> bool:
def dfs(index:int, node: TrieNode) -> bool:
# 如果已经检查完单词的所有字母
if index == len(word):
# 如果是单词的结尾, 则返回 True
return node.isLast
# 获取当前字母
w = word[index]
# 如果当前字母不是通配符
if w != '.':
# 计算字母的索引
c = ord(w) - ord('a')
# 获取相应的子节点
child = node.children[c]
# 如果子节点存在, 递归搜索下一个字母
if child is not None and dfs(index+1, child):
return True
# 如果是通配符
else:
# 遍历所有可能的子节点
for nc in node.children:
# 如果子节点存在, 递归搜索下一个字母
if nc is not None and dfs(index+1,nc):
# 返回True, 如果找到匹配的路径
return True
# 如果没有找到匹配的路径, 返回 False
return False
# 从根节点开始深度优先搜索
return dfs(0, self.li)
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)