Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the WordDictionary class:
WordDictionary()Initializes the object.void addWord(word)Addswordto the data structure, it can be matched later.bool search(word)Returnstrueif there is any string in the data structure that matcheswordorfalseotherwise.wordmay contain dots'.'where dots can be matched with any letter.
Example:
Input
["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
Output
[null,null,null,null,false,true,true,true]
Explanation
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
wordDictionary.search("pad"); // return False
wordDictionary.search("bad"); // return True
wordDictionary.search(".ad"); // return True
wordDictionary.search("b.."); // return True
Constraints:
1 <= word.length <= 500wordinaddWordconsists lower-case English letters.wordinsearchconsist of'.'or lower-case English letters.- At most
50000calls will be made toaddWordandsearch.
也是一道前缀树(Trie Tree)的上手题,跟LeetCode 208. Implement Trie (Prefix Tree)几乎一样,唯一不同是本题查找的字符串里可能有字符 '.',表示可以匹配任意字符,因此当遇到 '. '时,需要扫描当前节点下的所有子节点(即整棵子树,可以BFS或DFS进行扫描),只要能找到一个匹配的单词即可。
class TrieNode:
def __init__(self):
self.end = False
self.children = [None] * 26
class WordDictionary:
def __init__(self):
self.root = TrieNode()
def addWord(self, word: str) -> None:
node = self.root
for c in word:
idx = ord(c) - ord('a')
if not node.children[idx] :
node.children[idx] = TrieNode()
node = node.children[idx]
node.end = True
def search(self, word: str) -> bool:
return self.helper(self.root, word, 0)
def helper(self, node, word, i):
if not node :
return False
if i == len(word):
return node.end
if word[i] != '.':
idx = ord(word[i]) - ord('a')
return self.helper(node.children[idx], word, i + 1)
else:
for tmpNode in node.children:
if not tmpNode:
continue
if self.helper(tmpNode, word, i + 1):
return True
return False
