/*******************************************************************************
【字典树】
此模板主要是针对都是小写字母的。其他情况在此基础上改一改就可以了,要懂得灵活运用。
********************************************************************************/
struct trie /*字典树的节点内容*/
{
int count;/*计算该节点出现的次数*/
trie *next[26];/*一个节点有26个指针(孩子),即'a'-'z'*/
};
trie *root;
trie* newtrie()/*建立一个节点。(也可以用建立个大的数组,指针指向数组不同位置)*/
{
trie *t;
t=(trie*)malloc(sizeof(struct trie));
memset(t,0,sizeof(struct trie));
return t;
}
void Insert(char *ch) /*插入函数,将该字符串插入到字典树中 */
{
int i;
trie *t,*s;
s=root;
for(i=0;ch[i];i++)
{
if(s->next[ch[i]-'a'])
{
s=s->next[ch[i]-'a'];
s->count=s->count+1;
}
else
{
t=newtrie();
s->next[ch[i]-'a']=t;
s=t;
s->count=1;
}
}
}
int Search(char *ch)/*搜索函数,返回0则代表字典树不存在该字符串,反之亦然 */
{
int i;
trie *s=root;
if(ch[0]==0) return 0;
for(i=0;ch[i];i++)
{
if(s->next[ch[i]-'a'])
s=s->next[ch[i]-'a'];
else
break;
}
if(ch[i]==0) return s->count;
else return 0;
}
void Delete(char *ch)/*删除函数,将该字符串从字典树中删除(删除之前记得事先判断存不存在该字符串)*/
{
int i;
trie *s;
s=root;
for(i=0;ch[i];i++)
{
s=s->next[ch[i]-'a'];
s->count=s->count-1;
}
}
字典树 模板
最新推荐文章于 2019-11-19 17:00:04 发布