一、简介
Trie,又称前缀树或字典树,是一棵有根树,一般应用于字符串(本文假设字符串全为小写英文字母构成)的操作,其每个节点包含以下字段:
- 指向子节点的指针数组 children ,对于全为小写英文字母的字符串而言, children 数组长度为 26,即小写英文字母的数量。
- 布尔字段 isEnd ,表示该节点是否为字符串的结尾。
二、构造
class Trie {
private:
vector<Trie *> children;
bool isEnd;
Trie *searchPrefix(string pre)
{
Trie *node=this;
for(char c:pre)
{
c-='a';
if(!node->children[c]) return NULL;
node=node->children[c];
}
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(char c:word)
{
c-='a';
if(!node->children[c]) node->children[c]= new Trie();
node=node->children[c];
}
node->isEnd=true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
Trie *node=searchPrefix(word);
return node && node->isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Trie *node=searchPrefix(prefix);
return node;
}
};
三、应用
1、神奇的字典(简单应用)
力扣https://leetcode-cn.com/problems/US1pGT/
2、最短的单词编码(后缀树)