指针版:
初始化以及构建:
struct node {
int cnt;
node* child[26];
};
node* root;
void init()
{
root=new node();
}
插入处理:
void insert(const char s[])
{
node* now=root;
for(int i=0;s[i];i++){
int go=s[i]-'a';
if(now->child[go]==NULL)
now->child[go]=new node();
now=now->child[go];
now->cnt++;
}
}
查找处理:
int query(const char s[])
{
node* now=root;
for(int i=0;s[i];i++){
int go=s[i]-'a';
if(now->child[go]==NULL) return -1;
now=now->child[go];
}
return now->cnt;
}
删除处理:
这个删除处理得讲一下,它删除的东西跟输入进去的s【】数组有关,从s【】数组的头开始,一一删除对应的点,当然,如果在删除的中间过程发现到不匹配,则立刻返回,不再进行处理。
void del(const char s[])
{
node* now=root;
for(int i=0;s[i];i++){
int go=s[i]-'a';
if(now->child[go]->cnt==1){
now->child[go]=NULL;
return;
}
now=now->child[go];
now->cnt--;
}
}
完整的指针字典树,可以拿去自己测试、学习的代码:
#include <bits/stdc++.h>
using namespace std;
struct node {
int cnt;
node* child[26];
};
node* root;
void init()
{
root=new node();
}
void insert(const char s[])
{
node* now=root;
for(int i=0;s[i];i++){
int go=s[i]-'a';
if(now->child[go]==NULL)
now->child[go]=new node();
now=now->child[go];
now->cnt++;
}
}
int query(const char s[])
{
node* now=root;
for(int i=0;s[i];i++){
int go=s[i]-'a';
if(now->child[go]==NULL) return -1;
now=now->child[go];
}
return now->cnt;
}
void del(const char s[])
{
node* now=root;
for(int i=0;s[i];i++){
int go=s[i]-'a';
if(now->child[go]->cnt==1){
now->child[go]=NULL;
return;
}
now=now->child[go];
now->cnt--;
}
}
int main()
{
init();
insert("abcdef");
insert("abccba");
cout << query("abc") << endl;
cout << query("abcc") << endl;
cout << query("abs") << endl;
cout << query("abcdef") << endl;
del("abcdef");
cout << query("abcdef") << endl;
cout<<query("abc")<<endl;
return 0;
}
与指针相同,接下来我直接给出数组模拟的完整代码:
//数组模拟
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5;
struct node {
int cnt;
int child[26];
} trie[maxn * 30];
int tot, root;
int newnode()
{
tot++;
trie[tot].cnt = 0;
for(int i = 0; i < 26; i++) trie[tot].child[i] = -1;
return tot;
}
void init()
{
tot = -1;
root = newnode();
}
void insert(const char s[])
{
int now = root;
for(int i = 0; s[i]; i++) {
int go = s[i] - 'a';
if(trie[now].child[go] == -1) trie[now].child[go] = newnode();
now = trie[now].child[go];
trie[now].cnt++;
}
}
void del(const char s[])
{
int now = root;
for(int i = 0; s[i]; i++) {
int go = s[i] - 'a';
if(trie[trie[now].child[go]].cnt == 1) {
trie[now].child[go] = -1;
return;
}
now = trie[now].child[go];
trie[now].cnt--;
}
}
int query(const char s[])
{
int now = root;
for(int i = 0; s[i]; i++) {
int go = s[i] - 'a';
if(trie[now].child[go] == -1) return -1;
now = trie[now].child[go];
}
return trie[now].cnt;
}
int main()
{
init();
insert("abcdef");
insert("abccba");
cout << query("abc") << endl;
cout << query("abcc") << endl;
cout << query("abs") << endl;
cout << query("abcdef") << endl;
del("abcdef");
cout << query("abcdef") << endl;
cout<<query("abc")<<endl;
return 0;
}