設計添加和搜尋單字
「設計新增和搜尋單字」問題的詳細指南和 Python 實作。
1. 學習
「設計新增和搜尋單字」問題是 Trie 部分的關鍵挑戰。
此實作著重於 Python 中的簡單層級邏輯。
在我們提供的解決方案中,我們優先考慮技術準確性和程式碼可讀性。
2. Real-World Applications
3. Visual Intuition
視覺化設計新增和搜尋單字的邏輯流程。
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
仔細閱讀設計添加和搜尋單字的問題陳述。
2. Formulate brute force
起草一個簡單的迭代解決方案。
3. Identify inefficiency
尋找冗餘計算。
4. Optimize search path
使用散列或排序來加速該過程。
5. Final Implementation
清理生產標準代碼。
問題陳述
設計一個資料結構,支援新增單字並尋找字串是否與任何先前新增的字串相符。
實作 WordDictionary 類別:
- WordDictionary() 初始化物件。
- addWord(word: str) 將word加入資料結構中,稍後可以進行比對。
- search(word: str) -> bool 如果資料結構中存在與 word 相符的任何字串,則傳回 True,否則傳回 False。單字可能包含點“.”其中點可以與任何字母相符。
輸入是操作和參數的清單。實作一個函數 wordDictionary(operations: list, arguments: list) -> list 傳回結果清單(建構子/addWord 為 None,搜尋為 bool)。
- •1 <= len(word) <= 25
- •word in addWord consists of lowercase English letters
- •word in search consists of '.' or lowercase English letters
- •At most 10^4 calls will be made to addWord and search
範例
operations = ["WordDictionary", "addWord", "addWord", "addWord", "search", "search", "search", "search"], arguments = [[], ["bad"], ["dad"], ["mad"], ["pad"], ["bad"], [".ad"], ["b.."]]
[None, None, None, None, False, True, True, True]
Initialize. Add "bad", "dad", "mad". search("pad") -> False. search("bad") -> True. search(".ad") -> True. search("b..") -> True.
Need a Hint?
Edge Cases to Watch
- 空輸入結構
- 單元素輸入
- 大數值範圍
準備好解決了嗎?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
面試見解和變化
複雜度分析分解
為什麼時間: Directly evaluates all possibilities.
為什麼選擇太空: Uses standard local memory.
為什麼時間: Optimized paths reduce total operations.
為什麼選擇太空: May trade memory for speed.
最佳化解決方案Python程式碼
最佳化解決方案Python程式碼
class TrieNode:
def __init__(self):
self.children = {}
self.end = False
class WordDictionaryOpt:
def __init__(self):
self.root = TrieNode()
def addWord(self, word):
curr = self.root
for c in word:
if c not in curr.children: curr.children[c] = TrieNode()
curr = curr.children[c]
curr.end = True
def search(self, word):
def dfs(j, root):
curr = root
for i in range(j, len(word)):
c = word[i]
if c == ".":
for child in curr.children.values():
if dfs(i + 1, child): return True
return False
else:
if c not in curr.children: return False
curr = curr.children[c]
return curr.end
return dfs(0, self.root)暴力破解代碼(劇透保護)
暴力破解代碼(劇透保護)
class WordDictionaryBrute:
def __init__(self):
self.words = set()
def addWord(self, word):
self.words.add(word)
def search(self, word):
if '.' not in word: return word in self.words
for w in self.words:
if len(w) == len(word):
match = True
for i in range(len(word)):
if word[i] != '.' and word[i] != w[i]:
match = False; break
if match: return True
return FalseAlgorithm Pattern Checklist
When dealing with Trie data patterns.
- Are constraints clear?
- Is there a linear or logarithmic optimization possible?
PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!
推薦的 Python 資源
透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。
Python 嘗試/例外與錯誤處理
防止 Python 腳本崩潰。了解 try、 except、finally 區塊以及如何正確引發自訂異常。
如何在Python中產生隨機數(random模組)
了解如何在 Python 中產生隨機數。將 randrange、randint 和均勻浮點產生與播種控制進行比較。
Python pip 套件管理器備忘單
pip 命令列參考指南。学习安装、升级、卸载和管理 Python 包和依赖项。
Python 與 JavaScript:哪種程式語言最好?
Python 和 JavaScript 的全面比較。探索語法差異、效能、用例(後端與前端)和編碼範例。