字典树模板

本文介绍了一种利用字典树进行高效字符串匹配的方法。字典树能够利用字符串的公共前缀减少查询时间,提高效率。文章详细展示了字典树的构建过程及如何通过它查询特定前缀出现的次数,并提供了完整的代码示例。

字典树核心思想是利用字符串的公共前缀来降低查询时间的开销以达到提高效率的目的。


通过图上大家可以看出它可以迅速的查询单词的覆盖问题,寻找前缀。直接上代码

HDU1251

题意就是给你一堆字符串,到空格结束,然后给再给你一堆串,求每给你一个串,在第一堆串中有多少以此为前缀。

所以核心分为两部分,第一部分是建树,第二部分是查找。

#include <iostream>
#include <algorithm>
#include <string.h>
#include <string>
#include <cstdio>

using namespace std;

char s[25];
string ss;
struct tree{
    int t;               //这个很灵活,依题而定,在这里可以用来表示经过这个结点的单词的个数
    tree *next[30];      //记录结点下的字符,有二十六个英文字母。
    tree()
    {
        t = 0;
        memset(next, NULL, sizeof(next));
    }
};
tree *root;

void Insert()                          //建树
{
    tree *f = root;
    int k;
    int len = strlen(s);
    for(int i = 0; i < len; i++)
    {
        k = s[i] - 'a';
        if(f -> next[k] == NULL)
        {
            f -> next[k] = new tree;
        }
        f = f -> next[k];
        f -> t += 1;
    }
}

int Search()         //查找
{
    int len = ss.length();
    int k;
    tree *f = root;
    for(int i = 0; i < len; i++)
    {
        k = ss[i] - 'a';
        if(f -> next[k] == NULL)
            return 0;
        f = f -> next[k];
    }
    return f -> t;
}

int main()
{
    root = new tree;
    while(1)
    {
        int t = 0;
        do{
            scanf("%c", &s[t]);
        }while(s[t++] != '\n');
        if(s[0] == '\n')
            break;
        s[t - 1] = '\0';
        Insert();
    }
    while(cin >> ss)
    {
        int ans = Search();
        cout << ans << endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值