字典树模板(链式)

struct Node
{
    int cnt;
    Node *next[26];
    bool exist;
    Node()
    {
        cnt = 0;
        memset(next,0,sizeof(next));
        exist = false; 
    }   
}*rt;//要在主函数第一行写上 rt = new Node; 


void Insert(string str)//往字典树中插入一个字符串
{
    int a;
    Node *p = rt;
    int i = 0;
    while(str[i]!='\0')
    {
        a = str[i] - 'a';
        if(p->next[a] == NULL)
        {
            p->next[a] = new Node;
            p->next[a]->cnt = 0;
        }
        p = p->next[a];

        p->cnt += 1;
        ++i;
    }
    p->exist = true;
}

int QueryCnt(string str)//查询某前缀(str)的单词有多少个
{
    int a;
    Node *p = rt;

    int i = 0;
    while(str[i] && p!=NULL)
    {
        a = str[i] - 'a';
        p = p->next[a];
        ++i;
    }

    if(p == NULL)
        return 0;
    else
        return p->cnt;
}

bool Queryword(string str)//查询字典树中有没有字符串str
{
    int a;
    Node *p = rt;

    int i = 0;
    while(str[i] && p!=NULL)
    {
        a = str[i] - 'a';
        p = p->next[a];
        ++i;
    }
    if(p == NULL)
        return 0;
    if(p->exist==false)
        return 0;
    return true;
}
posted @ 2018-03-30 00:38  Apale  阅读(110)  评论(0编辑  收藏  举报