字典树代码分析
class Trie {
// 字典树的类
private:
Trie* next[26];// 是否有后续
int times;// 判断频次
public:
Trie() {// 初始化字典树
for (int i = 0; i < 26; i++) next[i] = nullptr;
times = 0;
}
void insert(string word) {
Trie* node = this;// 当前根节点
for (auto& ch : word) {
if (node->next[ch - 'a'] == nullptr) {
node->next[ch - 'a'] = new Trie();
}// 若当前字符串的字母不在时,创建新的一个节点
node = node->next[ch - 'a'];
}
node->times++;
}
int search(string word) {
Trie* node = this;
for (auto& ch : word) {
if (node->next[ch - 'a'] == nullptr) return 0;
node = node->next[ch - 'a'];
}
return node->times;// 返回频次
}
};
// 定义一个解决方法
class Solution{
private:
Trie* trie;
public:
solution(vector<string>& book) {
trie = new Trie();
for (auto& word : book) {
trie->insert(word);
}
}
int get(string word) {
return trie->search(word);
}
};