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;
}