当前位置:网站首页>208.实现Trie树(字典树与哈希表实现)
208.实现Trie树(字典树与哈希表实现)
2022-07-30 05:39:00 【Linke66】
1 字典树
Trie树又称字典树,字典树的数据结构如下所示;
下面这颗字典树包含的字符串集合是{ab,aza};
每一个类Trie中包含一个vector<Trie*>children(26),和isEnd(标记一个字符串的尾);
比如我们要插入abc,先看根节点node中的的children[a-‘a’]是否有指向下一个Trie的指针,有的话代表存在第一个字符为‘a’的前缀,那么往下走,node=node->children[a-'a‘];
再看这个节点的children[b-‘a’]中有指向下一个Trie的指针,往下走,node=node->children[b-'a’];
再看这个节点的children[c-‘a’]中,没有指向下一个Trie的指针,那么就在children[c-‘a’]中存放一个Trie*指针,代表指向的Trie,继续往下走到刚刚新建的Trie,node=node->children[c-'a’];一个abc的前缀到此创建完成,node->isEnd置为true,代表这里是前缀的终点。
class Trie {
vector<Trie*>children;
bool isEnd;
Trie* searchWord(const string& word){
Trie* node=this;
for(const char& w:word){
int ch=w-'a';
if(node->children[ch]==nullptr)
return nullptr;
node=node->children[ch];
}
return node;
}
public:
/** Initialize your data structure here. */
Trie():children(26),isEnd(false) {
}
/** Inserts a word into the trie. */
void insert(string word) {
Trie*node=this;
for(const char& w:word){
int ch=w-'a';
if(node->children[ch]==nullptr)
node->children[ch]=new Trie();
node=node->children[ch];
}
node->isEnd=true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
Trie* node=searchWord(word);
return node!=nullptr&&node->isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Trie*node=searchWord(prefix);
return node!=nullptr;
}
};
/** * Your Trie object will be instantiated and called as such: * Trie* obj = new Trie(); * obj->insert(word); * bool param_2 = obj->search(word); * bool param_3 = obj->startsWith(prefix); */
2 哈希表
对比不使用字典树,用哈希表集合set的做法
每一次查看是否有以prefix为前缀的字符串,都要在遍历集合中所有字符串,并进行一一比对,直到找到前缀为prefix的字符串,效率不如字典树。
class Trie {
unordered_set<string>st;
public:
/** Initialize your data structure here. */
Trie() {
}
/** Inserts a word into the trie. */
void insert(string word) {
st.insert(word);
}
/** Returns if the word is in the trie. */
bool search(string word) {
if(st.count(word))
return true;
return false;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
int n=prefix.size();
for(auto word:st){
if(word.size()<n) continue;
int i;
for(i=0;i<n;++i){
if(word[i]!=prefix[i])
break;
}
if(i==n) return true;
}
return false;
}
};
/** * Your Trie object will be instantiated and called as such: * Trie* obj = new Trie(); * obj->insert(word); * bool param_2 = obj->search(word); * bool param_3 = obj->startsWith(prefix); */
3 字典树较哈希表的优势
1 字典树的查询效率是O(logL),L是字符串的长度,效率高;
2字典树支持动态查询,当我们要查询apple时,hash必须等用户把单词apple输入完毕才能hash查询。而字典是则可以。
但是字典树比较耗费空间资源。
边栏推荐
- pwn-ROP
- numpy中np.inf函数的用法讲解
- Detailed MySQL-Explain
- MySql的初识感悟,以及sql语句中的DDL和DML和DQL的基本语法
- 4、nerf(pytorch)
- 质数(清华大学机试题)(DAY 86)
- Basic syntax of MySQL DDL and DML and DQL
- Different lower_case_table_names settings for server ('1') and data dictionary ('0') solution
- [Image processing] Image skeleton extraction based on central axis transformation with matlab code
- Prime numbers (Tsinghua University computer test questions) (DAY 86)
猜你喜欢
2022年比若依更香的开源项目
Different lower_case_table_names settings for server (‘1‘) and data dictionary (‘0‘) 解决方案
【图像检测】基于灰度图像的积累加权边缘检测方法研究附matlab代码
分布式事务之 LCN框架的原理和使用(二)
【线性神经网络】线性回归 / 基础优化方法
MySql模糊查询大全
安装Nuxt.js时出现错误:TypeError:Cannot read property ‘eslint‘ of undefined
MySQL user authorization
torch.load()
Teach you how to design a CSDN system
随机推荐
分布式事务之 LCN框架的原理和使用(二)
The difference between asyncawait and promise
使用DataEase开源工具制作一个高质量的数据大屏
从底层结构开始学习FPGA(6)----分布式RAM(DRAM,Distributed RAM)
k折交叉验证(k-fold Cross-validation)
[GO语言基础] 一.为什么我要学习Golang以及GO语言入门普及
爬虫数据是如何收集和整理的?
MySQL-Explain详解
839. Simulated heap
mysql time field is set to current time by default
Basic syntax of MySQL DDL and DML and DQL
net start mysql MySQL service is starting. MySQL service failed to start.The service did not report any errors.
ezTrack-master使用教程
idea 编译protobuf 文件的设置使用
坠落的蚂蚁(北京大学考研机试题)
“tensorflow.keras.preprocessing“ has no attribute “image_dataset_from_directory“
My first understanding of MySql, and the basic syntax of DDL and DML and DQL in sql statements
[GO Language Basics] 1. Why do I want to learn Golang and the popularization of GO language entry
Personal blog system (with source code)
131.分割回文串