(1)
字典树,又称单词查找树,Trie树,是一种树形结构,哈希表的一个变种。用于统计,排序和保存大量的字符串(也可以保存其
的)。
优点就是利用公共的前缀来节约存储空间。在这举个简单的例子:比如说我们想储存3个单词,nyist、nyistacm、nyisttc。如果只是
单纯的按照以前的字符数组存储的思路来存储的话,那么我们需要定义三个字符串数组。但是如果我们用字典树的话,只需要定义
一个树就可以了。在这里我们就可以看到字典树的优势了。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
#define N 10000010
char s[N];
char word[N];
int cnt;
typedef struct node
{
int flg;
struct node *child[26];
} trie;
trie* init_trie()
{
trie *root;
root = (trie *)malloc(sizeof(trie));
root->flg = 0;
for(int i = 0; i < 26; i++)
root->child[i] = NULL;
return root;
}
void insert_trie(trie *root, char *s)
{
trie *r = root;
char *p = s;
while(*p)
{
if(r->child[*p - 'a'] == NULL)
r->child[*p - 'a'] = init_trie();
r = r->child[*p - 'a'];
p++;
}
r->flg = 1;
}
int search_trie(trie *root, char *s)
{
trie *r = root;
char *p = s;
while(*p && r)
{
r = r->child[*p - 'a'];
p++;
}
if(r && r->flg)
return 0;
else
{
cnt++;
insert_trie(root, s);
return 1;
}
}
int main()
{
while(gets(s), strcmp(s, "#") != 0)
{
cnt = 0;
int len = strlen(s);
trie *root = init_trie();
for(int i = 0; i < len; i++)
{
if(s[i] >= 'a' && s[i] <= 'z')
{
int k = 0;
while(s[i] >= 'a' && s[i] <= 'z')
{
word[k++] = s[i];
i++;
}
word[k] = '\0';
i--;
search_trie(root, word);
}
}
memset(s, 0, sizeof(s));
printf("%d\n", cnt);
}
return 0;
}
(3)需要注意的事项
首先是在判断一个单词是否存在时 ,不仅仅是看所有的字母是否匹配,还要看最后一个匹配的字母是否可以作为一个单词的结尾,然后就是要是想要看某个前缀出现了多少次,用一个变量来记录一下。