字典树(查询前缀和,判断字符串是否存在)

字典树

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
struct node {//节点
	int next[26];//根据保存数据类型,只有小写或大写时填26,大小写都有时52,只有数字时10,根据需要改变
	int v;//判断前缀个数
	bool IsWord;//判断单词是否存在
	void init() {//初始化
		v=0;
		IsWord=false;
		memset(next,-1,sizeof(next));
	}
} a[1000005];
int tol=0;//保存下一个节点的位置
void Insert(char s[],int len) {//插入函数
	int now=0;
	for(int i=0; i<len; i++) {
		int tmp=s[i]-'a';
		if(a[now].next[tmp]==-1) {
			a[now].next[tmp]=++tol;
			a[tol].init();
		}
		now=a[now].next[tmp];
		a[now].v++;
	}
	a[now].IsWord=true;
}
int Query_Pre(char s[],int len) {//查询前缀个数
	int now=0;
	for(int i=0; i<len; i++) {
		int tmp=s[i]-'a';
		if(a[now].next[tmp]==-1)
			return 0;
		now=a[now].next[tmp];
	}
	return a[now].v;
}
bool Query_IsWord(char s[],int len) { //判断单词是否存在
	int now=0;
	for(int i=0; i<len; i++) {
		int tmp=s[i]-'a';
		if(a[now].next[tmp]==-1)
			return false;
		now=a[now].next[tmp];
	}
	return a[now].IsWord;
}
char s[100];
int main() {//主函数实现,可根据题意改变
	int k;
	a[0].init();
	string op;
	while(1) {
		cin>>op;
		if(op=="end"){
			break;
		} 
		if(op=="add") {
			scanf("%s",s);
			Insert(s,strlen(s));
		} else if(op=="pre") {
			scanf("%s",s);
			printf("%d\n",Query_Pre(s,strlen(s)));
		} else if(op=="wor") {
			scanf("%s",s);
			if( Query_IsWord(s,strlen(s))) {
				printf("Yes\n");
			} else {
				printf("No\n");
			}
		} 
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值