先给大家介绍一下什么是字典树。
字典树,顾名思义,是树的一种,哈希树的变种,优点是节省存储空间,优化查询效率。
数据结构:
typedef struct _node {
Node *child[26]; //指向下一个字母,因为英文字母只有26个
int n; //表示前缀数目
bool flag; //表示是否以改字母结尾(按题目需要增加)
…… //其余内容可以根据题目要求进行增加
}Node;
下图是以ban,bag,bee,cat,cap,ca这6个单词构成的字典树:有三角形表示flag为true,没有表示false
字典树的插入操作:
void Insert (Node *root, char *str)
{//向以root为根的树中加入字符串str
int len = strlen (str);
Node *ans = root;
for (int i =0; i < len; i ++)
{
if (ans->child[str[i] - 'a'] == NULL)//没有该字母
{
Node *NewNode = (Node *) malloc (sizeof (Node)); //建立节点
//初始化
NewNode->n = 1;
for (int j = 0; j < 26; j++)
{
NewNode->child[j] = NULL;
}
ans->child[str[i] - 'a'] = NewNode;
ans = NewNode;
}
else
{
ans = ans->child[str[i] - 'a']; //找下一个字母
ans->n ++; //统计前缀数目
}
}
}
以下为1251的实现代码:
#include <iostream>
using namespace std;
char ch1[100000][20];
//char ch1[10][20];
char ch2[20];
typedef struct Node
{
Node *child[26];
int n;
}Node;
void Insert (Node *root, char *str)
{
int len = strlen (str);
Node *ans = root;
for (int i =0; i < len; i ++)
{
if (ans->child[str[i] - 'a'] == NULL)
{
Node *NewNode = (Node *) malloc (sizeof (Node));
NewNode->n = 1;
for (int j = 0; j < 26; j++)
{
NewNode->child[j] = NULL;
}
ans->child[str[i] - 'a'] = NewNode;
ans = NewNode;
}
else
{
ans = ans->child[str[i] - 'a'];
ans->n ++;
}
}
}
int Search (Node *root, char *str)
{
int len = strlen (str);
Node *ans = root;
int i;
for (i = 0; i < len; i ++)
{
if (ans->child[str[i] - 'a'] != NULL)
{
ans = ans->child[str[i] - 'a'];
}
else
{
break;
}
}
if (i == len)
{
return ans->n;
}
return 0;
}
int main ()
{
Node *root = (Node *)malloc (sizeof (Node));
root->n = 0;
int i;
for (i = 0; i < 26; i++)
{
root->child[i] = NULL;
}
i = 1;
while (1)
{
gets (ch1[i]);
if (ch1[i][0] == 0)
{
break;
}
Insert (root, ch1[i]);
i ++;
}
while (gets (ch2) != NULL)
{
cout<<Search (root, ch2)<<endl;
}
}