当前为游客只读模式。登录后可提交代码判题并保存草稿与进度。

练题计划 · 力扣 HOT 100

实现前缀树

中等trie()
时间限制 2000 ms内存限制 128 MB复杂度要求 时间 插入/查找 O(L),空间 O(字符集 * L * n)

实现前缀树(Trie)

实现一个前缀树(Trie)类,支持 insert、search 和 startsWith 三个操作。

与力扣原题语义一致,此处采用函数式接口:传入操作名数组和参数数组,依次执行并返回每次操作的结果。

接口

  • operations[0] 恒为 "Trie"(构造,跳过)。
  • 后续每个操作名对应 words[i] 作为参数:
  • "insert":插入字符串,返回 null
  • "search":查找字符串是否存在,返回 boolean
  • "startsWith":查找是否有以该前缀开头的字符串,返回 boolean

输入

  • operations:操作名数组,首项为 "Trie"
  • words:与 operations 等长的参数数组;insert/search/startsWith 时为对应字符串

输出

按顺序返回每个非构造操作的结果:insert 返回 null,search/startsWith 返回布尔值。

示例一

输入:

operations = ["Trie", "insert", "search", "startsWith"]
words = ["", "apple", "apple", "app"]

输出:

[null, true, true]

示例二

输入:

operations = ["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
words = ["", "apple", "apple", "app", "app", "app", "app"]

输出:

[null, true, false, true, null, true]

示例三

输入:

operations = ["Trie", "search"]
words = ["", "a"]

输出:

[false]
Loading...

输入

[["Trie","insert","search","startsWith"],["","apple","apple","app"]]

预期输出

[null,true,true]
自定义用例