150强访谈中等

实现 Trie 前缀树

“实现 Trie 前缀树”问题的详细指南和 Python 实现。

问题陈述

中等

trie(发音为“try”)或前缀树是一种树数据结构,用于有效地存储和检索字符串数据集中的键。这种数据结构有多种应用,例如自动完成和拼写检查。

实现 Trie 类:

- Trie() 初始化 trie 对象。

- insert(word: str) 将字符串 word 插入到 trie 中。

- search(word: str) -> bool 如果字符串 word 在 trie 中(即之前插入过),则返回 True,否则返回 False。

-startsWith(prefix:str)->bool 如果先前插入的字符串单词具有前缀 prefix,则返回 True,否则返回 False。

输入是操作和参数的列表。实现一个函数 trie(operations: list, arguments: list) -> list 返回结果列表(构造函数/插入为 None,搜索/startsWith 为 bool)。

约束条件
  • 1 <= len(word), len(prefix) <= 2000
  • word and prefix consist of lowercase English letters
  • At most 3 * 10^4 calls will be made in total to insert, search, and startsWith

示例

Example 1
Input
operations = ["Trie", "insert", "search", "search", "startsWith", "insert", "search"], arguments = [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output
[None, None, True, False, True, None, True]
Explanation

Trie initialized. insert("apple"). search("apple") returns True. search("app") returns False. startsWith("app") returns True. insert("app"). search("app") returns 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 资源

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