一 描述
Trie,又称单词查找树或键树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计和排序大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:最大限度地减少无谓的字符串比较,查询效率比哈希表高。
二
本题是要根据词典,来翻译句子,数据结构
struct trie_node
{
char trans[11];//翻译
bool is_has; //是否在词典存在
struct trie_node *next[num];//儿子节点
};
三 代码
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#define num 26
struct trie_node
{
char trans[11];
bool is_has;
struct trie_node *next[num];
};
static struct trie_node root;
void insert(char *s, char* t)
{
struct trie_node *curr = &root;
struct trie_node *newnode = NULL;
while(*s)
{
if (curr->next[*s-'a'] == NULL)
{
newnode = (struct trie_node*) malloc(sizeof(struct trie_node));
memset(newnode, 0, sizeof(struct trie_node));
curr->next[*s-'a'] = newnode;
}
curr = curr->next[*s-'a'];
++s;
}
curr->is_has = true;
strcpy(curr->trans, t);
}
char* find(char* s)
{
struct trie_node *curr = &root;
char* t =s;
while(*t)
{
if (curr->next[*t-'a'] != NULL)
{
curr = curr->next[*t-'a'];
++t;
}
else
return s;
}
if (curr->is_has)
return curr->trans;
else
return s;
}
int main()
{
freopen("in.txt", "r", stdin);
char s1[1003];
char s2[1003];
scanf("%s", s1);
while (scanf("%s", s1) && strcmp(s1, "END") != 0)
{
scanf("%s", s2);
insert(s2, s1);
}
getchar();
gets(s1);
int c;
int ith = 0;
while ( (c = getchar()) != 'E')
{
if (c >= 'a' && c <= 'z')
s2[ith++] = c;
else
{
s2[ith] = '\0';
if (ith != 0)
printf("%s", find(s2));
printf("%c", c);
ith = 0;
}
}
return 0;
}