• 【LeetCode】208.实现Trie(前缀树)


    题目

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

    请你实现 Trie 类:

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

    示例:

    输入
    ["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
    [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
    输出
    [null, null, true, false, true, null, true]
    
    解释
    Trie trie = new Trie();
    trie.insert("apple");
    trie.search("apple");   // 返回 True
    trie.search("app");     // 返回 False
    trie.startsWith("app"); // 返回 True
    trie.insert("app");
    trie.search("app");     // 返回 True
    

    提示:

    • 1 <= word.length, prefix.length <= 2000
    • word 和 prefix 仅由小写英文字母组成
    • insertsearch 和 startsWith 调用次数 总计 不超过 3 * 10^4 次

    解答

    源代码

    1. class Trie {
    2. private Trie[] children;
    3. private boolean isEnd;
    4. public Trie() {
    5. children = new Trie[26];
    6. isEnd = false;
    7. }
    8. public void insert(String word) {
    9. Trie node = this;
    10. for (int i = 0; i < word.length(); i++) {
    11. char ch = word.charAt(i);
    12. int index = ch - 'a';
    13. if (node.children[index] == null) {
    14. node.children[index] = new Trie();
    15. }
    16. node = node.children[index];
    17. }
    18. node.isEnd = true;
    19. }
    20. public boolean search(String word) {
    21. return searchPrefix(word) != null && searchPrefix(word).isEnd;
    22. }
    23. public boolean startsWith(String prefix) {
    24. return searchPrefix(prefix) != null;
    25. }
    26. private Trie searchPrefix(String prefix) {
    27. Trie node = this;
    28. for (int i = 0; i < prefix.length(); i++) {
    29. char ch = prefix.charAt(i);
    30. int index = ch - 'a';
    31. if (node.children[index] == null) {
    32. return null;
    33. }
    34. node = node.children[index];
    35. }
    36. return node;
    37. }
    38. }
    39. /**
    40. * Your Trie object will be instantiated and called as such:
    41. * Trie obj = new Trie();
    42. * obj.insert(word);
    43. * boolean param_2 = obj.search(word);
    44. * boolean param_3 = obj.startsWith(prefix);
    45. */

    总结

    有些复杂啊……第一次没折腾出来放弃了,第二次才AC了。

    官解用的其实相当于一个26叉数,成员变量children数组表示的是下一个字母,0索引对应' a ',25索引对应' z ';isEnd表示当前字母是否为一个单词的末尾。

  • 相关阅读:
    分布式系统的认证授权
    进程基本概念
    产品经理进阶:外包原因及类型(一)
    Android Studio Chipmunk | 2021.2.1 Patch 2(2022 年 8 月)
    React18原理: React核心对象之Update、UpdateQueue、Hook、Task对象
    读高性能MySQL(第4版)笔记14_备份与恢复(中)
    vite自定义打包路径
    ctfhub-web-warmup
    TensorRT ubuntu18.04 安装过程记录
    【老生谈算法】matlab在材料力学中的应用
  • 原文地址:https://blog.csdn.net/qq_57438473/article/details/132597321