LeeCode——208. 实现 Trie (前缀树)(Java)

题目描述

题干:
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

题解思路

又是一道设计题,这次让你设计前缀树的对象模型,需要完成的有初始化、插入元素、搜索元素和判断前缀

我们因为要判断元素存在,而且要添加新的元素,所以我们在树中要定义新的节点和判断是否为结尾的标志

初始化的话,就是定义新的节点和将结尾标记置为false

添加元素就看是否字符串已经存在,存在的话就不做处理,不存在的话就添加新的节点并将标志置位true

查找元素就是遍历判断该字符串是否存在,查找前缀就必须得从头开始判断每个字符串

这两个查找相比差别就是查找的标志为true,而前缀的标志位false

正确代码

package LeetCode.daily_practice;

class Trie {

    private Trie[] children;
    private boolean isEnd;

    /**
     * Initialize your data structure here.
     */
    public Trie() {
        children = new Trie[26];
        isEnd = false;
    }

    /**
     * Inserts a word into the trie.
     */
    public void insert(String word) {
        Trie node = this;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            int index = ch - 'a';
            if (node.children[index] == null) {
                node.children[index] = new Trie();
            }
            node = node.children[index];
        }
        node.isEnd = true;
    }

    /**
     * Returns if the word is in the trie.
     */
    public boolean search(String word) {
        Trie node = searchPrefix(word);
        return node != null && node.isEnd;
    }

    /**
     * Returns if there is any word in the trie that starts with the given prefix.
     */
    public boolean startsWith(String prefix) {
        return searchPrefix(prefix) != null;
    }

    private Trie searchPrefix(String prefix) {
        Trie node = this;
        for (int i = 0; i < prefix.length(); i++) {
            char ch = prefix.charAt(i);
            int index = ch - 'a';
            if (node.children[index] == null) {
                return null;
            }
            node = node.children[index];
        }
        return node;
    }
}

总结

这个称为前缀树或者是字典树的结构一开始我以为是一种类似于前缀遍历的结构,但是其实并没有关联

其实这里的isEnd的状态我也很懵,总感觉在search的时候并没有给isEnd赋值,总感觉有逻辑错误

如果文章存在什么问题或者有更好的题解,欢迎在评论区斧正和评论,各自努力,你我最高处见
posted @ 2021-04-14 09:06  21岁还不是架构师  阅读(65)  评论(0编辑  收藏  举报