150強訪談簡單

設計添加和搜尋單字

「設計新增和搜尋單字」問題的詳細指南和 Python 實作。

問題陳述

簡單

設計一個資料結構,支援新增單字並尋找字串是否與任何先前新增的字串相符。

實作 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

範例

Example 1
Input
operations = ["WordDictionary", "addWord", "addWord", "addWord", "search", "search", "search", "search"], arguments = [[], ["bad"], ["dad"], ["mad"], ["pad"], ["bad"], [".ad"], ["b.."]]
Output
[None, None, None, None, False, True, True, True]
Explanation

Initialize. Add "bad", "dad", "mad". search("pad") -> False. search("bad") -> True. search(".ad") -> True. search("b..") -> True.

Need a Hint?
考慮使用 Trie 特定的資料結構,例如集合或堆疊。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。