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

本文介绍了Trie(前缀树)的数据结构,包括其概念、应用场景以及如何在Java中实现Trie类的insert、search和startsWith方法。通过实例演示了如何构造Trie并执行相关操作。

在这里插入图片描述

🚀 算法题 🚀

🌲 算法刷题专栏 | 面试必备算法 | 面试高频算法 🍀
🌲 越难的东西,越要努力坚持,因为它具有很高的价值,算法就是这样✨
🌲 作者简介:硕风和炜,优快云-Java领域优质创作者🏆,保研|国家奖学金|高中学习JAVA|大学完善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

提示:

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

🌟 求解思路&实现代码&运行结果


⚡ 前缀树

🥦 求解思路
  1. 前缀树是一种用于快速查询某个字符串或者字符前缀是否存在的数据结构。核心是使用边来代表有无字符,使用点来记录是否为单词结尾以及其后续字符串的字符。
  2. 定义一个TrieNode类,end表示有无字符串以当前字符结尾,TrieNode[]表示26个TrieNode数组,保存了对当前结点而言下一个可能出现的所有字符的链接。
  3. 插入操作:从根结点的子结点开始与 word每一个字符进行匹配,如果前缀树上没有对应的字符,开始不断new新的结点,直到插入完 word 的最后一个字符,同时还要将最后一个结点end = true,表示它是一个单词的末尾。
  4. 查找操作:从根结点的子结点开始,一直向下匹配,如果出现结点值为空就返回 false,如果匹配到了最后一个字符,只需判断 node.end即可。
  5. 前缀操作:和查找操作类似,只是不需要判断最后一个字符结点的end,因为可以匹配到最后一个字符,肯定有单词以prefix为前缀。
  6. 有了基本的思路,接下来我们就来通过代码来实现一下。
🥦 实现代码
class Trie {

    class TrieNode {
        boolean end;
        TrieNode[] tries = new TrieNode[26];
    }

    TrieNode root;

    public Trie() {
        root = new TrieNode();
    }

    public void insert(String word) {
        TrieNode node = root;
        for (int i = 0; i < word.length(); i++) {
            int index = word.charAt(i) - 'a';
            if (node.tries[index] == null) {
                node.tries[index] = new TrieNode();
            }
            node = node.tries[index];
        }
        node.end = true;
    }

    public boolean search(String word) {
        TrieNode node = root;
        for (int i = 0; i < word.length(); i++) {
            int index = word.charAt(i) - 'a';
            if (node.tries[index] == null) {
                return false;
            }
            node = node.tries[index];
        }
        return node.end;
    }

    public boolean startsWith(String prefix) {
        TrieNode node = root;
        for (int i = 0; i < prefix.length(); i++) {
            int index = prefix.charAt(i) - 'a';
            if (node.tries[index] == null) {
                return false;
            }
            node = node.tries[index];
        }
        return true;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */
🥦 运行结果

在这里插入图片描述


💬 共勉

最后,我想和大家分享一句一直激励我的座右铭,希望可以与大家共勉!

在这里插入图片描述

在这里插入图片描述

### 实现 Trie前缀) 为了实现 Trie 据结构,在 Java 中可以定义一个 `TrieNode` 类来表示节点,并创建相应的操作方法。下面是一个完整的解决方案: #### 定义 Trie 节点 每个节点包含指向其子节点的链接列表以及是否为单词结束标志。 ```java class TrieNode { private final int R = 26; private TrieNode[] links; private boolean isEnd; public TrieNode() { links = new TrieNode[R]; } // 判断是否存在字符对应的子节点 public boolean containsKey(char ch) { return links[ch - 'a'] != null; } // 获取指定字符对应的孩子结点 public TrieNode get(char ch) { return links[ch - 'a']; } // 设置当前结点孩子结点 public void put(char ch, TrieNode node) { links[ch - 'a'] = node; } // 标记该位置是否有字符串终止于此处 public void setEnd() { isEnd = true; } // 是否有字符串在此终结 public boolean isEnd() { return isEnd; } } ``` #### 创建 Trie 类并提供接口函 通过封装上述基本功能,可构建更高级别的 API 来支持插入、搜索和查询以特定前缀开头的所有键等功能。 ```java class Trie { private final TrieNode root; /** Initialize your data structure here. */ public Trie() { root = new TrieNode(); } /** Inserts a word into the trie. */ public void insert(String word) { TrieNode node = root; for (int i = 0; i < word.length(); i++) { char currentChar = word.charAt(i); if (!node.containsKey(currentChar)) { node.put(currentChar, new TrieNode()); } node = node.get(currentChar); } node.setEnd(); } /** Returns if the word is in the trie. */ public boolean search(String word) { TrieNode 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) { TrieNode node = searchPrefix(prefix); return node != null; } private TrieNode searchPrefix(String word) { TrieNode node = root; for (int i = 0; i < word.length(); i++) { char curLetter = word.charAt(i); if (node.containsKey(curLetter)) { node = node.get(curLetter); } else { return null; } } return node; } } /** * Your Trie object will be instantiated and called as such: * Trie obj = new Trie(); * obj.insert(word); * boolean param_2 = obj.search(word); * boolean param_3 = obj.startsWith(prefix); */ ``` 此代码实现Trie 的核心逻辑,包括初始化、插入新词、查找完整匹配项以及检查给定前缀的存在性[^1]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

硕风和炜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值