字典树--代码模板

  • 查找该字符串是不是已经出现过
//在给出的字符串中查找当前字符串是否出现过
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <string>
#include <deque>
#include <map>
#define INF 0x3f3f3f3f
#define FRE() freopen("in.txt","r",stdin)

using namespace std;
typedef long long ll;
const int maxn = 1e5 + 5;
int tot,n;
int trie[maxn][26];
//bool isw[maxn];//查询整个单词用

void Insert(char* str, int rt)
{
    for(int i = 0; str[i]; i++)
    {
        int x = str[i] - 'a';
        if(trie[rt][x] == 0)//当前插入的字母在之前同一节点处没有出现过
        {
            trie[rt][x] = tot++;//字母出入新位置,否则不作处理
        }
        rt = trie[rt][x];//为下一个字母的插入做准备
    }
    //isw[rt] = true;//标志该单词最后字母的尾节点,在查询整个单词时用到
}


bool _Find(char *str,int rt)
{
    for(int i = 0; str[i]; i++)
    {
        int x = str[i] - 'a';
        if(trie[rt][x] == 0) return false;//以rt为头结点的x字母不存在,返回0
        rt = trie[rt][x];//为查询下个字母做准备
    }
    return true;
}


char s[22];
int main()
{
    tot = 0;
    int rt = 1;
    scanf("%d",&n);
    for(int i = 1; i <= n; i++)
    {
        scanf("%s",s);
        Insert(s, rt);
    }
    scanf("%d",&n);
    for(int i = 1; i <= n; i++)
    {
        scanf("%s",&s);
        if(_Find(s, rt))
            printf("YES\n");
        else
            printf("NO\n");
    }
    return 0;
}
  • 统计前缀和出现的次数
//查询前缀出现的次数
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <string>
#include <deque>
#include <map>
#define INF 0x3f3f3f3f
#define FRE() freopen("in.txt","r",stdin)

using namespace std;
typedef long long ll;
const int maxn = 1e5 + 5;
int trie[400001][26],len,root,tot,sum[400001];
bool p;
int n,m; 
char s[11];

void insert()
{
    len=strlen(s);
    root=0;
    for(int i=0;i<len;i++)
    {
        int id=s[i]-'a';
        if(!trie[root][id]) trie[root][id]=++tot;
        sum[trie[root][id]]++;//前缀后移一个位置保存 
        root=trie[root][id];
    }
}
int search()
{
    root=0;
    len=strlen(s);
    for(int i=0;i<len;i++)
    {
        int id=s[i]-'a';
        if(!trie[root][id]) return 0;
        root=trie[root][id];
    }//root经过此循环后变成前缀最后一个字母所在位置的后一个位置 
    return sum[root];//因为前缀后移了一个保存,所以此时的sum[root]就是要求的前缀出现的次数 
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        cin>>s;
        insert();
    }
    scanf("%d",&m);
    for(int i=1;i<=m;i++)
    {
        cin>s;
        printf("%d\n",search());
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值