LeetCode_前缀树_中等_208.实现 Trie (前缀树)

短命女 2023-10-06 22:53 74阅读 0赞

目录

  • 1.题目
  • 2.思路
  • 3.代码实现(Java)

1.题目

Trie(发音类似 “try”)或者说前缀树是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。(下图来自网络)

在这里插入图片描述

请你实现 Trie 类:

  1. Trie() 初始化前缀树对象。
  2. void insert(String word) 向前缀树中插入字符串 word
  3. boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false
  4. boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false

示例:

  1. 输入
  2. ["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
  3. [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
  4. 输出
  5. [null, null, true, false, true, null, true]
  6. 解释
  7. Trie trie = new Trie();
  8. trie.insert("apple");
  9. trie.search("apple"); // 返回 True
  10. trie.search("app"); // 返回 False
  11. trie.startsWith("app"); // 返回 True
  12. trie.insert("app");
  13. trie.search("app"); // 返回 True

提示:
1 <= word.length, prefix.length <= 2000
word 和 prefix 仅由小写英文字母组成
insert、search 和 startsWith 调用次数总计不超过 3 * 104 次

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/implement-trie-prefix-tree

2.思路

(1)前缀树
思路参考本题官方题解。
前缀树本质上就是一棵从二叉树衍生出来的多叉树,但是它和之前的普通多叉树节点不同,其节点中 children 数组的索引是有意义的,它代表键中的一个字符。

3.代码实现(Java)

  1. //思路1————前缀树
  2. class Trie {
  3. private Trie[] children;
  4. private boolean isEnd;
  5. public Trie() {
  6. //每个节点最多有 26 个子节点,分别对应 26 个小写英文字母
  7. children = new Trie[26];
  8. isEnd = false;
  9. }
  10. //插入字符串
  11. public void insert(String word) {
  12. Trie node = this;
  13. for (int i = 0; i < word.length(); i++) {
  14. char ch = word.charAt(i);
  15. int index = ch - 'a';
  16. if (node.children[index] == null) {
  17. node.children[index] = new Trie();
  18. }
  19. node = node.children[index];
  20. }
  21. node.isEnd = true;
  22. }
  23. //搜索字符串
  24. public boolean search(String word) {
  25. Trie node = searchPrefix(word);
  26. return node != null && node.isEnd;
  27. }
  28. //判断前缀 prefix 是否存在于前缀树中
  29. public boolean startsWith(String prefix) {
  30. return searchPrefix(prefix) != null;
  31. }
  32. //返回前缀 prefix 的最后一个字符所在的节点
  33. public Trie searchPrefix(String prefix) {
  34. Trie node = this;
  35. for (int i = 0; i < prefix.length(); i++) {
  36. char ch = prefix.charAt(i);
  37. int index = ch - 'a';
  38. if (node.children[index] == null) {
  39. return null;
  40. }
  41. node = node.children[index];
  42. }
  43. return node;
  44. }
  45. }
  46. /**
  47. * Your Trie object will be instantiated and called as such:
  48. * Trie obj = new Trie();
  49. * obj.insert(word);
  50. * boolean param_2 = obj.search(word);
  51. * boolean param_3 = obj.startsWith(prefix);
  52. */

发表评论

表情:
评论列表 (有 0 条评论,74人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Leetcode208. 实现 Trie (前缀)

    前言 蒟蒻做题。 已有工作 字典树又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常