Problem
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)
Addsword
to the data structure, it can be matched later.bool search(word)
Returnstrue
if there is any string in the data structure that matchesword
orfalse
otherwise.word
may contain dots'.'
where dots can be matched with any letter.
https://leetcode.com/problems/design-add-and-search-words-data-structure/
Example 1:
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
1
2
3
4
5
6
7
8 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 <= 25
word
inaddWord
consists of lowercase English letters.word
insearch
consist of'.'
or lowercase English letters.- There will be at most
2
dots inword
forsearch
queries. - At most
10⁴
calls will be made toaddWord
andsearch
.
Test Cases
1 | class WordDictionary: |
1 | import pytest |
Thoughts
208. Implement Trie (Prefix Tree) 里的 trie 树正好适合这个问题。
在原来的 search
方法上增加模糊匹配的功能。即如果 word
当前的字符是 .
就遍历所有的子树。
为了避免混淆, 把 trie 标识单词结束的符号换成
#
了(Problem 208 中用的是.
)。
直接用递归写就比较简单。
也可以用栈加循环避免递归。
Code
Recursively
1 | class WordDictionary: |
Non-recursively
1 | class WordDictionary: |
刻意将非递归方法写的跟递归的处理逻辑能对应上,可以注意从递归改为非递归时所做的调整。实际上就是树的深度优先遍历,这里将
node
设置为None
来标识路径已经结束,可以从栈里弹出其他待处理的节点。