前缀树
0、题目
力扣:
208、实现Trie树
212、单词搜索2
1、概念
参考:https://blog.csdn.net/u011764940/article/details/121970140
概念:Trie树,即字典树,又称单词查找树或键树,是一种多叉树结构,是一种哈希树的变种。典型应用是用于统计和排序大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:最大限度地减少无谓的字符串比较。
图片理解可参考博客。
2、实现
class Trie {
private:
string word;
unordered_map<char, Trie *> children;
public:
Trie() {
word = "";
}
void insert(string word) {
Trie *node = this;
for (auto it : word) {
if (node->children.count(it) == 0) {
node->children[it] = new Trie();
}
node = node->children[it];
}
node->word = word;
}
bool search(string word) {
Trie *node = this;
for (char ch : word) {
if (node->children.count(ch) == 0) {
return false;
}
node = node->children[ch];
}
return node->word.size() != 0;
}
bool startsWith(string prefix) {
Trie *node = this;
for (auto ch : prefix) {
if (node->children.count(ch) == 0) {
return false;
}
node = node->children[ch];
}
return true;
}
};