LeetCode 208. Implement Trie (Prefix Tree) 实现 Trie (前缀树)(C++/Java)
题目:
Implement a trie with insert, search, and startsWith methods.
Example:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // returns true
trie.search("app"); // returns false
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app"); // returns true
Note:
- You may assume that all inputs are consist of lowercase letters
a-z. - All inputs are guaranteed to be non-empty strings.
分析:
实现一个前缀树,包含insert, search, and startsWith三个方法,分别对应插入,搜索单词和搜索前缀三个方法。
前缀树在这里就不多说了,网上的介绍有很多。
下面说一下具体的实现。
因为只有a-z共26个英文字母,所有开辟一个26大小的数组用来保存节点,isEnd用来表示该节点是否为单词终止节点,例如apple,那么在e节点时应该将isEnd置为true,以便搜索方法查询单词。
Trie* node[26] = {nullptr};
bool isEnd = false;
insert插入一个单词,遍历单词的每一个字符,从根节点开始查询对应位置的数组是否为空,如果为空就在对应位置新建节点,然后继续,在最后一个字符对应的位置isEnd记为true
void insert(string word) {
Trie* p = this;
for(const char ch:word){
if(p->node[ch-'a'] == nullptr)
p->node[ch-'a'] = new Trie();
p = p->node[ch-'a'];
}
p->isEnd = true;
}
search, and startsWith可以通过一个辅助函数来实现,遍历单词的字符,如果对应位置为null则表示前缀树中没有这个字符,返回null即可,否自返回查询到的最后一个结点。通过结点来判断单词是否存在,如果isEnd为true则search返回true。
Trie* mySearch(string word){
Trie *p = this;
for (auto c : word){
if (p->node[c - 'a'] == nullptr) return nullptr;
p = p->node[c - 'a'];
}
return p;
}
程序:
C++
class Trie {
public:
/** Initialize your data structure here. */
Trie() {
//root = new Trie();
}
/** Inserts a word into the trie. */
void insert(string word) {
Trie* p = this;
for(const char ch:word){
if(p->node[ch-'a'] == nullptr)
p->node[ch-'a'] = new Trie();
p = p->node[ch-'a'];
}
p->isEnd = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
Trie* res = mySearch(word);
return res && res->isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
return mySearch(prefix) != nullptr;
}
private:
//Trie* root;
Trie* node[26] = {nullptr};
bool isEnd = false;
Trie* mySearch(string word){
Trie *p = this;
for (auto c : word){
if (p->node[c - 'a'] == nullptr) return nullptr;
p = p->node[c - 'a'];
}
return p;
}
};
Java
class Trie {
/** Initialize your data structure here. */
public Trie() {
}
/** Inserts a word into the trie. */
public void insert(String word) {
Trie p = this;
char[] w = word.toCharArray();
for(char ch:w){
if(p.node[ch - 'a'] == null)
p.node[ch - 'a'] = new Trie();
p = p.node[ch - 'a'];
}
p.isEnd = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
Trie res = find(word);
return res != null && res.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
return find(prefix) != null;
}
private Trie[] node = new Trie[26];
private boolean isEnd = false;
private Trie find(String word){
Trie p = this;
char[] w = word.toCharArray();
for(char ch:w){
if(p.node[ch - 'a'] == null)
return null;
p = p.node[ch - 'a'];
}
return p;
}
}
/**
* 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);
*/
LeetCode 208. Implement Trie (Prefix Tree) 实现 Trie (前缀树)(C++/Java)的更多相关文章
- 【LeetCode】208. Implement Trie (Prefix Tree) 实现 Trie (前缀树)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 公众号:负雪明烛 本文关键词:Leetcode, 力扣,Trie, 前缀树,字典树,20 ...
- Leetcode: Implement Trie (Prefix Tree) && Summary: Trie
Implement a trie with insert, search, and startsWith methods. Note: You may assume that all inputs a ...
- Leetcode208. Implement Trie (Prefix Tree)实现Trie(前缀树)
实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作. 示例: Trie trie = new Trie(); trie.insert(" ...
- 字典树(查找树) leetcode 208. Implement Trie (Prefix Tree) 、211. Add and Search Word - Data structure design
字典树(查找树) 26个分支作用:检测字符串是否在这个字典里面插入.查找 字典树与哈希表的对比:时间复杂度:以字符来看:O(N).O(N) 以字符串来看:O(1).O(1)空间复杂度:字典树远远小于哈 ...
- [LeetCode] 208. Implement Trie (Prefix Tree) ☆☆☆
Implement a trie with insert, search, and startsWith methods. Note:You may assume that all inputs ar ...
- 【LeetCode】208. Implement Trie (Prefix Tree)
Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith methods. Note:You ...
- 【刷题-LeetCode】208. Implement Trie (Prefix Tree)
Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith methods. Example: ...
- leetcode面试准备:Implement Trie (Prefix Tree)
leetcode面试准备:Implement Trie (Prefix Tree) 1 题目 Implement a trie withinsert, search, and startsWith m ...
- LeetCode208 Implement Trie (Prefix Tree). LeetCode211 Add and Search Word - Data structure design
字典树(Trie树相关) 208. Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith ...
- [LeetCode] 208. Implement Trie (Prefix Tree) 实现字典树(前缀树)
Implement a trie with insert, search, and startsWith methods. Example: Trie trie = new Trie(); trie. ...
随机推荐
- iframe跨域,获取iframe中元素
1.需求让iframe嵌入页面,并且没有滚动条,也就是相当于两个页面拼接在一起 跨域解决,通过框架配置代理 proxy: { '/medical': { target: 'https://exampl ...
- flutter 移动应用程序中打开URL
url_launcher: ^6.2.5 在Flutter中,url_launcher库是用于在移动应用程序中打开URL的常用工具.它允许你通过调用系统的浏览器或其他应用程序来打开指定的URL,比 ...
- 二叉查找树的实现C/C++
二叉查找树是一种关键字有序存放的二叉树.在不含重复关键字的二叉查找树中,关键字"较小"的节点一定在关键字"较大"的节点的左子树中,"较小"一 ...
- 暑期集训 Day11 —— 模拟赛复盘
${\color{Green} \mathrm{Problem\ 1 :Subarray }} $ 签到失败... 直接二进制分组,找出所有二进制位=0 的方法. 死因: 二进制分组没想出来... $ ...
- 手把手教你PolarDB-X中的表设计——用户表
简介: 本系列旨在描述一个具体的业务场景,给出建表的例子,帮助大家更好的使用PolarDB-X.本期的主题是:用户表. 本系列旨在描述一个具体的业务场景,给出建表的例子,帮助大家更好的使用PolarD ...
- 消息队列 RocketMQ 遇上可观测:业务核心链路可视化
简介:本篇文章主要介绍 RocketMQ 的可观测性工具在线上生产环境的最佳实践.RocketMQ的可观测性能力领先业界同类产品,RocketMQ 的 Dashboard 和消息轨迹等功能为业务核心 ...
- 最佳实践丨云上虚拟IDC(私有池)如何为客户业务的确定性、连续性保驾护航
简介: 企业业务上云后,还面临特定可用区购买云上特定计算产品实例失败的困境?云上私有池pick一下 Why 云上业务为什么需要资源确定性.服务连续性 云计算正朝着像水电煤一样的基础设施演进,支持用户 ...
- 不只有 Spring,这四款 Java 基础开发框架同样值得关注! 审核中
Java 开发不只有 Spring ,今天给大家推荐几个同样优秀的 Java 基础开发框架,为日常项目开发提供更多的选择.答应我,请不要再叫我 Spring 小子了,好吗? 项目概览: Guice: ...
- Intel Pentium III CPU(Coppermine, Tualatin) L2 Cache Latency, Hardware Prefetch特性调查
这几天,偶然的机会想到了困扰自己和其他网友多年的Intel Pentium III系列处理器缓存延迟(L2 Cache Latency),以及图拉丁核心版本是否支持硬件预取(Hardware Pref ...
- SAP UI5 官方教程学习记录
最近有闲跟着官方的Get Started教程学习了UI5,记录一下自己学习中遇到的几个问题. 本文链接:https://www.cnblogs.com/hhelibeb/p/17835722.html ...