这里给出两篇讲解非常详细的字典树博客:
https://blog.csdn.net/piaocoder/article/details/47836559
https://blog.csdn.net/SunnyYoona/article/details/43900425
第一篇更注重于算法模板,而第二篇更注重于算法讲解。
这里给出综合两篇文章的算法代码:
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
const int maxn=50000+10;
const int INF=0x3f3f3f3f;
struct node
{
int cnt;
node *next[26];
node()
{
cnt=0;
memset(next,0,sizeof(next));
}
};
void buildTire(string s)
{
node *p=root;
node *temp=NULL;
int len=s.size();
for(int i=0;i<len;i++)
{
if(p->next[s[i]-'a']==NULL)
{
temp=new node();
p->next[s[i]-'a']=temp;
}
p=p->next[s[i]-'a'];
p->cnt++;
}
}
void findTire(string s)
{
node *p=root;
int len=s.size();
for(int i=0;i<len;i++)
{
if(p->next[s[i]-'a']==NULL)
{
printf("未找到\n");
return;
}
p=p->next[s[i]-'a'];
}
printf("%d\n",p->cnt);//输出相关信息
}
void delTire(nodee *root)
{
for(int i=0;i<26;i++)
{
if(root->next[i])
{
delTire(root->next[i]);
}
}
delete(root);
}