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 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。