LeetCode208 实现 Trie (前缀树) Java
2021/10/19 17:10:58
本文主要是介绍LeetCode208 实现 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
-
提示
1 <= word.length, prefix.length <= 2000
word
和prefix
仅由小写英文字母组成insert
、search
和startsWith
调用次数 总计 不超过 3 * 104 次
思路 :
- 字典树
示例一:
class Trie { // 子节点 private Trie[] child; // 是否结尾 private boolean isEnd; public Trie() { // 只有小写字母故直接初始化26个,若child[i]!=null 则代表该字母存在。i=char-'a' child=new Trie[26]; } public void insert(String word) { char[] chars = word.toCharArray(); Trie node = this; for (char c : chars) { // 判断该字母是否已存在,不存在则创建 if (node.child[c - 'a'] == null) { node.child[c - 'a'] = new Trie(); } node = node.child[c - 'a']; } // 表示该节点是某个单词的结尾 node.isEnd = true; } public boolean search(String word) { Trie node = searchPrefix(word); return node != null && node.isEnd; } public boolean startsWith(String prefix) { return searchPrefix(prefix) != null; } // 获取前缀的最后一个字符 Trie,null代表不存在 public Trie searchPrefix(String prefix) { Trie node = this; char[] chars = prefix.toCharArray(); for (char c : chars) { if (node.child[c - 'a'] == null) { return null; } node = node.child[c - 'a']; } return node; } }
结果:
这篇关于LeetCode208 实现 Trie (前缀树) Java的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)