Trie [traɪ] 读音和 try 相同,它的另一些名字有:字典树,前缀树,单词查找树等。
字典树
包含三个单词“sea”,“sells”,"she"的Trie的样子:
定义类Trie
class Trie {
private:
bool isEnd;
Trie* next[26];
public:
//插入
//查找
//前缀匹配
};
插入
向Trie中插入一个单词word
首先从根节点的子结点开始与word的第一个字符进行匹配,一直到前缀链上没有对应的字符,这时不断地开辟新的结点,直到插入完word的最后一个字符。
同时还要将最后一个结点 isEnd=true,表示它是一个单词的末尾
void Trie::insert(string word){
Trie* node = this;
for (char c : word) {
if (node->next[c - 'a'] == nullptr) {
node->next[c - 'a'] = new Trie();
}
node = node->next[c - 'a'];
}
//将最后一个结点设为isEnd=true,表示一个单词的末尾
node->isEnd = true;
}
查找
查找Trie中是否存在单词word
从根节点的子节点开始,一直向下匹配,如果出现节点值为null则返回false。
如果匹配到了最后一个字符,判断node->isEnd并返回。
bool Trie::search(string word) {
Trir* node = this;
for (char c : word) {
node = node->next[c - 'a'];
if (node == nullptr) {
return false;
}
return node->isEnd;
}
}
前缀匹配
判断Trie中是否有以prefix为前缀的单词
类似于search,不需要判断最后一个字符结点的isEnd
bool Trie::startsWith(string prefix) {
Trie* node = this;
for (char c : prefix) {
node = node->next[c - 'a'];
if (node == nullptr) {
return false;
}
}
return true;
}
总结:
- Trie的形状和单词插入或删除顺序无关,也就是说对于任意给定的一组单词,Trie的形状都是唯一的
- 查找或插入一个长度为L的单词,访问next数组的次数最多为L+1,和Trie中包含多少个单词无关。
- Trie的每个结点中都保留着一个字母表,这是很耗费空间的。如果Trie的高度为n,字母表的大小为m,最坏的情况是Trie中还不存在前缀相同的单词,那空间复杂度就为
。
208. 实现 Trie (前缀树) - 力扣(LeetCode)
class Trie {
private:
bool isEnd;
Trie* next[26];
public:
Trie() {
isEnd = false;
memset(next, 0, sizeof(next));
}
void insert(string word) {
Trie* node=this;
for(char c:word){
if(node->next[c-'a']==nullptr){
node->next[c-'a']=new Trie();
}
node=node->next[c-'a'];
}
node->isEnd=true;
}
bool search(string word) {
Trie* node=this;
for(char c:word){
node=node->next[c-'a'];
if(node==nullptr){
return false;
}
}
return node->isEnd;
}
bool startsWith(string prefix) {
Trie* node=this;
for(char c:prefix){
node=node->next[c-'a'];
if(node==nullptr){
return false;
}
}
return true;
}
};
/**
* 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);
*/
1804. 实现 Trie (前缀树) II - 力扣(LeetCode)
这里参考一个老哥的解法。。脱离了字典树的传统写法,用哈希表来实现,比较简洁
需要注意的是cnt+=it->second,而不是cnt++;
class Trie {
private:
unordered_map<string,int>m;
public:
Trie() {
m.clear();
}
void insert(string word) {
++m[word];
}
int countWordsEqualTo(string word) {
if(m.count(word)){
return m[word];
}
return 0;
}
int countWordsStartingWith(string prefix) {
int cnt=0;
for(auto it=m.begin();it!=m.end();++it){
if(it->first.find(prefix)==0){
cnt+=it->second;
}
}
return cnt;
}
void erase(string word) {
--m[word];
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* int param_2 = obj->countWordsEqualTo(word);
* int param_3 = obj->countWordsStartingWith(prefix);
* obj->erase(word);
*/