字典树,是一种存取字符串的树状存储结构,以字符串的每一个字符为结点,不断扩展。从根节点到叶子结点,途中经过的结点的值连接起来就是该字符串。该存储方式可以有效的减少空间的浪费,有很多字符串可以公用一些结点,减少了空间上的开支。在查找的时候也比较方便,若查询到某一个字符时,该结点不存在,那么该字符串必然不存在。
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
using namespace std;
#define maxn 26
//结点定义
typedef struct Trie
{
int cnt;
struct Trie* next[maxn];
}Trie;
Trie *root;
//初始化
void init()
{
root = new Trie;
root->cnt = 0;
for(int i=0; i<26; i++)
root->next[i] = NULL;
}
//插入单词
void Insert_Tree(char *s)
{
int len = strlen(s);
Trie *p = root,*q;
for(int i=0; i<len; i++)
{
int num = s[i] - 'a';
if(!p->next[num])
{
q = new Trie;
q->cnt = 0;
for(int j=0; j<26; j++)
q->next[j] = NULL;
p->next[num] = q;
}
p = p->next[num];
}
p->cnt++;
}
//单词查找
int Find_Tree(char *s)
{
int len = strlen(s);
Trie *p = root;
for(int i=0; i<len; i++)
{
int num = s[i] - 'a';
if(! p->next[num]) return 0;
p = p->next[num];
}
return p->cnt;
}
//销毁处理
void Free_Tree(Trie *t)
{
if(!t) return ;
for(int i=0; i<26; i++)
Free_Tree(t->next[i]);
delete t;
}
int main()
{
init();
int n;
scanf("%d",&n);
char str[10];
while(n--)
{
scanf("%s",str);
Insert_Tree(str);
}
int m;
scanf("%d",&m);
while(m--)
{
scanf("%s",str);
if(Find_Tree(str)) printf("Find\n");
else printf("Not Find\n");
}
Free_Tree(root);
}