https://zhuanlan.zhihu.com/p/28891541
https://www.cnblogs.com/fusiwei/p/11972776.html
Trie树,即字典树,又称单词查找树或键树,是一种树形结构。
利用字符串的公共前缀来降低查询时间的开销以达到提高效率的目的。
字典树理解:
字典树模板:
#include<iostream>
#include<cstring>
using namespace std;
const int N = 100010;
class Trie {
private:
int son[N][26]; //存放子结点信息
int cnt[N]; //存放数量
int idx; //字典树中结点编号,每个编号唯一
public:
Trie() {
memset(son, 0, sizeof(son));
memset(cnt, 0, sizeof(cnt));
idx = 0;
}
//字典树插入函数
void insert(string word) {
int p = 0;
for (int i = 0; i < word.size(); ++i) {
int u = word[i] - 'a';
if (!son[p][u]) son[p][u] = ++idx;
p = son[p][u];
}
cnt[p]++; //以某个字母结尾的单词有多少个
}
//字典树搜索函数
bool search(string word) {
int p = 0;
for (int i = 0; i < word.size(); ++i) {
int u = word[i] - 'a';
if (!son[p][u]) return false;
p = son[p][u];
}
if (cnt[p] > 0) return true;
else return false;
}
};