Trie树(字典树)

本文深入解析Trie树(字典树)的构建与应用,详细介绍了如何通过Trie树进行字符串的高效插入和查询操作,同时展示了统计前缀和的实现方法。通过具体的代码示例,读者可以了解到Trie树在实际编程中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Trie树又名字典树,是数据结构中基础而又重要的一部分内容。

Trie树的讲解请参考如下网址:

http://hihocoder.com/problemset/problem/1014

一.Trie树的建立 http://hihocoder.com/problemset/problem/1014#

二. Trie树的使用 http://hihocoder.com/problemset/problem/1014#

三. 在建立Trie树的同时统计前缀和 http://hihocoder.com/problemset/problem/1014#

Trie树的实现代码如下:

注意,Trie树插入和查询的时间复杂度均为O(N),其中N为单个字符串的长度。

即:

字典树的插入和查询操作的时间复杂度为O(strlen(str))

// Trie树(字典树)
#include <cstdio>
#include <cstring>
#include <iostream>
struct Trie // 建立节点
{
    int count; // count用于记录前缀和
    struct Trie *word[26]; // 建立一个指向结构体Trie的含有26个元素(26个字母)的word指针数组
    Trie() // 构造函数
    {
        count = 0; // 初始化
        for(int i = 0; i < 26; i++) // 初始化
        word[i] = NULL;
    }
};
void insert(Trie *root, char *str) // 插入一个字符串
{
    for(; *str; str++) // 当这个字符串没有到末尾时,继续沿着向后搜索遍历
    {
        if(root->word[*str-'a']) // 当root->word[*str - 'a'] != NULL时
        {
            root->word[*str-'a']->count++;
        }
        else
        {
            root->word[*str-'a'] = new Trie();
            root->word[*str-'a']->count++;
        }
        
        root=root->word[*str-'a']; // 更新root的指向,完善字典树
    //  printf("%c %d\t",*str,root->count);
    }
}
int search(Trie *root, char *str) // 查找Trie树中以该字符串为前缀的字符串的总数
{
    int count;
    while(*str) // 当这个字符串没有到末尾时
    {
        if(root->word[*str-'a']) // 如果root指向的节点(root的孩子)中有该字母,则更新root为孩子,继续搜索
        {
            root = root->word[*str-'a'];
            count = root->count;
        }
        else // 否则,直接返回0,代表以这个字符串为前缀的单词在整个字典树中出现的个数为0
        {
            count = 0;
            break;
        }
//      printf("--%d ",count);
        str++;
    }
    return count;
}
int main()
{
    int n,m;
    Trie *root = new Trie(); // 建立字典树的根root
    scanf("%d",&n);
    while(n--)
    {
        char str[20];
        scanf("%s", str);
        insert(root, str); // 将字符串插入字典树
    }   
    scanf("%d",&m);
    while(m--)
    {
        char str[20];
        scanf("%s", str);
        printf("%d\n", search(root,str)); // 查找字符串是否在字典树中
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值