Try Again

字典树

字典树通过链表来建树,可以删除,可以通过前缀来查找字典序里的已存的单词。

当一个单词结束时,标记成不同的颜色。

创建结点

struct trie
{
    int cnt;
    bool isend;
    struct trie *next[26];
    trie()
    {
        cnt=0;
        isend=false;
        for(int i=0;i<26;i++)
            next[i]=NULL;
    }
}

插入新单词

void buildtrie(trie *root,char *s)
{
    trie *p=root;
    trie *tmp;
    len=strlen(s);
    for(int i=0;i<len;i++)
    {
        if(p->next[s[i]-'a']==NULL)
        {
            tmp=new trie;
            p->next[s[i]-'a']=tmp;
        }
        p=p->next[s[i]-'a'];
        p-cnt++;
    }
    p->isend=true;
}

前缀查询

int findtrie(trie *root,char *s)
{
    trie *p=root;
    int len=strlen(s);
    for(int i=0;i<len;i++)
    {
        if(p->next[s[i]-'a']==NULL)
            return 0;
        p=p->next[s[i]-'a'];
    }
    return p->cnt;
}

释放内存

void del(trie *root)
{
    for(int i=0;i<26;i++)
    {
        if(root->next[i]!=NULL)
            del(root->next[i]);
    }
    free(root);
}

查询一个单词是否已经存在

nt insert_find(trie *root,char *s)
{
    trie *p=root;
    while(p!=NULL && *s!='\0')
    {
        p=p->next[*s-'a'];
        s++;
    }
    return (p!=NULL && p->isend==true);
}

 

posted @ 2017-07-03 20:37  十年换你一句好久不见  阅读(129)  评论(0编辑  收藏  举报