前缀树( 或称字典树),用于统计,排序和保存大量的字符串,利用字符串的公共前缀来减少查询时间,查询效率比哈希树高。
示例:

联想此图,很容易写出插入,查找,查找是否存在前缀等函数
class Trie {
bool is_end; // 当前是否是一个单词的结尾
Trie *next[26]; // 该节点往下
public:
/** Initialize your data structure here. */
Trie() {
is_end = false;
for(int i = 0; i < 26; ++i) next[i] = nullptr;
}
/** Inserts a word into the trie. */
void insert(string word) {
Trie *root = this;
for(int i = 0; i < word.size(); ++i)
{
if(root->next[word[i] - 'a'] == nullptr) root->next[word[i] - 'a'] = new Trie();
root = root->next[word[i] - 'a'];
}
root->is_end = true; // 最后一个单词的下一个结点标记为end
}
/** Returns if the word is in the trie. */
bool search(string word) {
Trie *root = this;
for(int i = 0; i < word.size(); ++i)
{
if(root->next[word[i] - 'a'] == nullptr) return false;
root = root->next[word[i] - 'a'];
}
return root->is_end;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Trie *root = this;
for(int i = 0; i < prefix.size(); ++i)
{
if(root->next[prefix[i] - 'a'] == nullptr) return false;
root = root->next[prefix[i] - 'a'];
}
return true;
}
};
本文深入讲解了前缀树(字典树)的概念,通过实例展示了如何利用前缀树进行字符串的高效统计、排序和保存。文章详细介绍了前缀树的插入、查找及前缀匹配等功能,并提供了代码实现。

被折叠的 条评论
为什么被折叠?



