字典树(1)--建立字典树,查询前缀是否出现过

360百科:又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。

通过建立树形结构 让有前缀相同的单词 前缀只出现一次,以此来减少查询时间,增加查询效率。

 

查询前缀是否出现过

数组实现

#include<stdio.h>
#include<string.h>
int trip[4000][26];
int tot = 1;
void insert(char s[11]) {  //插入  
	int root = 0;
	int len = strlen(s);
	for(int i=0; i<len; i++) {
		int id = s[i]-'a';
		if(!trip[root][id])  //如果树中没有出现过 那就加上,并且分配编号
			trip[root][id]=tot++;
		root = trip[root][id];
	}
}
bool serch(char s[11]) {
	int root = 0;
	int len = strlen(s);
	for(int i = 0 ; i<len; i++) {
		int id = s[i]-'a';
		if(trip[root][id]==0)  // 等于0 表示未出现过 直接返回false
			return false;
		root=trip[root][id];
	}
	return true;
}
int main() {
	char s[11];
	int n;
	scanf("%d",&n);
	while(n--) {
		scanf("%s",s);
		insert(s);
	}
	int m;
	scanf("%d",&m);
	while(m--) {
		scanf("%s",s);
		if(serch(s))
			printf("yes\n");
		else
			printf("no\n");
	}
	return 0;
}

结构体:

#include<stdio.h>
#include<string.h>
struct node {
	int count;
	node *next[26];
}*root;

int tot=1;

node *build() {    
	node *n = new node;
	n->count=0;
	memset(n->next,0,sizeof(n->next));
	return n;
}

void insert(char *s) {
	node *r =root;
	char *word = s;
	while(*word) {
		int id = *word-'a';
		if(r->next[id]==0)
			r->next[id]=build();
		r = r->next[id];
		r->count++;
		word++;
	}

}

bool serch(char *s) {

	node *r = root;
	char *word = s;
	while(*word) {
		int id = *word-'a';
		if(r->next[id]==0)
			return false;
		r=r->next[id];
		word++;
	}
	return true;
}

int main() {
	int n;
	root =build();
	char s[11];
	scanf("%d",&n);
	while(n--) {
		scanf("%s",s);
		insert(s);
	}
	int m;
	scanf("%d",&m);
	while(m--) {

		scanf("%s",s);
		if(serch(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、付费专栏及课程。

余额充值