Top 150 Interview簡単

Design Add And Search Words

Detailed guide and Python implementation for the 'Design Add And Search Words' 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.

- addWord(word: str) Adds word to the data structure, it can be matched later.

- search(word: str) -> bool Returns True if there is any string in the data structure that matches word or False otherwise. word may contain dots '.' where dots can be matched with any letter.

Input is a list of operations and arguments. Implement a function wordDictionary(operations: list, arguments: list) -> list that returns a list of results (None for constructor/addWord, bool for search).

制約
  • 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?
Consider using Trie-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

解決する準備はできましたか?

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 リソース

関連するインタラクティブなチュートリアル、チートシート、コード比較で知識を深めてください。