#include <bits/stdc++.h>
using namespace std;
const int MaxNode = 26;
struct Node {
int end;
int pass;
vector<Node *> nexts;
Node() : end(0), pass(0) {
nexts = vector<Node *>(MaxNode, nullptr);
};
};
class trie {
private:
Node *root;
public:
trie() : root(new Node()) {};
~trie() = default;
//插入字符串
void insert(string s);
//查询字符串出现过没有,没有就返回0,有就返回这个字符串加过几次
int search(string s);
//查询以该字符串做前缀加了多少个
int searchHead(string s);
//删除某个字符串
void Delete(string s);
};
void trie::insert(string s) {
if (s.empty()) return;
Node *node = root;
node->pass++;
int index = 0;
for (int i = 0; i < s.size(); ++i) {
index = s[i] - 'a';
if (node->nexts[index] == nullptr) {
node->nexts[index] = new Node();
}
node = node->nexts[index];
node->pass++;
}
node->end++;
}
int trie::search(string s) {
if (s.empty()) return 0;
Node *node = root;
int index = 0;
//记录出现过几次
for (int i = 0; i < s.size(); ++i) {
index = s[i] - 'a';
if (node->nexts[index] == nullptr) return 0;
node = node->nexts[index];
}
return node->end;
}
int trie::searchHead(string s) {
if (s.empty()) return 0;
Node *node = root;
int index = 0;
for (int i = 0; i < s.size(); ++i) {
index = s[i] - 'a';
if (node->nexts[index] == nullptr) return 0;
node = node->nexts[index];
}
return node->pass;
}
void trie::Delete(string s) {
if (s.empty()) {
cout << "error" << endl;
}
Node *node = root;
node->pass--;
int index = 0;
for (int i = 0; i < s.size(); ++i) {
index = s[i] - 'a';
node = node->nexts[index];
node->pass--;
}
node->end--;
}
//以上是针对字符串26个小写字母;
//如果字符扩展了到很大,我们可以用hash表来作为index(key) 和node *(value);