本文完整拆解 LeetCode 211 Design Add and Search Words Data Structure 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Design Add and Search Words Data Structure 一次弄懂。
Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link
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 <= 25wordinaddWordconsists of lowercase English letters.wordinsearchconsist of'.'or lowercase English letters.- There will be at most
2dots inwordforsearchqueries. - At most
104calls will be made toaddWordandsearch.
Python
# time complexity: O(M)
# space complexity: O(M)
class TrieNode:
def __init__(self):
self.children = {}
self.isEnd = False
class WordDictionary:
def __init__(self):
self.root = TrieNode()
self.maxLen = 0
def addWord(self, word: str) -> None:
node = self.root
l = 0
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
l += 1
self.maxLen = max(self.maxLen, l)
node.isEnd = True
def search(self, word: str) -> bool:
if len(word) > self.maxLen:
return False
def helper(idx, node):
for i in range(idx, len(word)):
if word[i] == ".":
for child in node.children.values():
if helper(i + 1, child):
return True
return False
else:
if word[i] not in node.children:
return False
node = node.children[word[i]]
return node.isEnd
return helper(0, self.root)
wordDictionary = WordDictionary()
wordDictionary.addWord("bad")
wordDictionary.addWord("dad")
wordDictionary.addWord("mad")
print(wordDictionary.search("pad"))
print(wordDictionary.search("bad"))
print(wordDictionary.search(".ad"))
print(wordDictionary.search("b.."))
Design Add and Search Words Data Structure 解題思路
這題在 Trie 之上加了萬用字元 “.”:遇到它時無法只走一條路,必須對所有子節點都試一次,所以 search 從迴圈變成遞迴(或 DFS)。addWord 完全沿用基本 Trie 的作法,複雜度的差異全部集中在 search。
Design Add and Search Words Data Structure 演算法步驟
- addWord:與基本 Trie 相同,逐字元建節點,終點標記 isEnd。
- search 定義為遞迴函式 dfs(node, index)。
- 若字元是一般字母,沒有對應子節點就回傳 false,否則往下遞迴。
- 若字元是 “.”,對所有子節點各遞迴一次,任一成功就回傳 true;索引走完時回傳 node.isEnd。
Design Add and Search Words Data Structure 複雜度分析
| 項目 | 複雜度 |
|---|---|
| 時間複雜度 | O(L) ~ O(26^L) |
| 空間複雜度 | O(N·L) |
沒有萬用字元時與一般 Trie 相同為 O(L);全部都是 “.” 的最壞情況要展開所有分支,上界為 O(26^L)。實務上字典稀疏,分支會迅速被剪掉。空間為 Trie 本身的 O(N·L) 加上遞迴深度 O(L)。
Design Add and Search Words Data Structure 的邊界情況與常見錯誤
- “.” 分支要對「存在的子節點」迭代,而不是對 26 個字母硬試。
- 索引走到結尾時一定要檢查 isEnd,否則前綴會被誤判為單字。
- 全部是 “.” 的查詢等同於問「有沒有長度為 L 的單字」。
- 大量萬用字元查詢時,可額外用長度分組來加速。
Design Add and Search Words Data Structure 其他解法比較
| 解法 | 時間 | 空間 | 說明 |
|---|---|---|---|
| 把所有單字存進集合用正則比對 | O(N·L) | O(N·L) | 每次查詢要掃全部單字 |
| 按長度分組後逐一比對 | O(N·L) | O(N·L) | 有剪枝但仍是線性掃描 |
| Trie + 萬用字元 DFS | O(L)~O(26^L) | O(N·L) | 本文採用 |
