字典树 模板

/*******************************************************************************

【字典树】

此模板主要是针对都是小写字母的。其他情况在此基础上改一改就可以了,要懂得灵活运用。 

********************************************************************************/

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;
    }   
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值