字典树模板(有待更新,链表版)

本文深入探讨了字典树(Trie)的数据结构特性,对比了链表版与数组版的不同,详细介绍了字典树的节点结构及其实现方法,包括节点创建、字符串插入与查找操作。

链表版:空间小,时间大。

数组版:空间大,时间小

struct node
{
    int num;
    node *next[maxn];
};

//字典树
class Tree{
public:
    node *head;
    //构造函数
    Tree()
    {
        head = New();
    }
    //创建一个新节点
    node* New()
    {
        node *p = new node();
        for (int i = 0; i < maxn; ++i)
        {
            p->next[i] = NULL;
        }
        p->num = 0;
        return p;
    }
    //插入一个字符串
    void insert(char *str)
    {
        int len = strlen(str);
        node *t, *p = head;
        for (int i = 0; i < len; ++i)
        {
            int c = str[i] - 'a';
            if (p->next[c] == NULL)
            {
                t = New();    //创建新的节点
                p->next[c] = t;
            }
                p = p->next[c];
                p->num++;
        }
    }
    int find(char *str)
    {
        node *p = head;
        int len = strlen(str);
        for (int i = 0; i < len; ++i)
        {
            int c = str[i] - 'a';
            if (p->next[c] == NULL)
                return 0;        //不存在这样的字符串
                p = p->next[c];
        }
        return p->num;
    }
};

良心模板

转载于:https://www.cnblogs.com/ALINGMAOMAO/p/10079035.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值