Trie树又名字典树,是数据结构中基础而又重要的一部分内容。
Trie树的讲解请参考如下网址:
http://hihocoder.com/problemset/problem/1014
一.Trie树的建立 http://hihocoder.com/problemset/problem/1014#
二. Trie树的使用 http://hihocoder.com/problemset/problem/1014#
三. 在建立Trie树的同时统计前缀和 http://hihocoder.com/problemset/problem/1014#
Trie树的实现代码如下:
注意,Trie树插入和查询的时间复杂度均为O(N),其中N为单个字符串的长度。
即:
字典树的插入和查询操作的时间复杂度为O(strlen(str))
// Trie树(字典树)
#include <cstdio>
#include <cstring>
#include <iostream>
struct Trie // 建立节点
{
int count; // count用于记录前缀和
struct Trie *word[26]; // 建立一个指向结构体Trie的含有26个元素(26个字母)的word指针数组
Trie() // 构造函数
{
count = 0; // 初始化
for(int i = 0; i < 26; i++) // 初始化
word[i] = NULL;
}
};
void insert(Trie *root, char *str) // 插入一个字符串
{
for(; *str; str++) // 当这个字符串没有到末尾时,继续沿着向后搜索遍历
{
if(root->word[*str-'a']) // 当root->word[*str - 'a'] != NULL时
{
root->word[*str-'a']->count++;
}
else
{
root->word[*str-'a'] = new Trie();
root->word[*str-'a']->count++;
}
root=root->word[*str-'a']; // 更新root的指向,完善字典树
// printf("%c %d\t",*str,root->count);
}
}
int search(Trie *root, char *str) // 查找Trie树中以该字符串为前缀的字符串的总数
{
int count;
while(*str) // 当这个字符串没有到末尾时
{
if(root->word[*str-'a']) // 如果root指向的节点(root的孩子)中有该字母,则更新root为孩子,继续搜索
{
root = root->word[*str-'a'];
count = root->count;
}
else // 否则,直接返回0,代表以这个字符串为前缀的单词在整个字典树中出现的个数为0
{
count = 0;
break;
}
// printf("--%d ",count);
str++;
}
return count;
}
int main()
{
int n,m;
Trie *root = new Trie(); // 建立字典树的根root
scanf("%d",&n);
while(n--)
{
char str[20];
scanf("%s", str);
insert(root, str); // 将字符串插入字典树
}
scanf("%d",&m);
while(m--)
{
char str[20];
scanf("%s", str);
printf("%d\n", search(root,str)); // 查找字符串是否在字典树中
}
return 0;
}