看了POJ上的一道题目,大致讲的是给出一方语言A词语所对应的另一方语言B的含义,然后给出B的一些词语,找到A所对应的翻译。显而易见,每个词语逻辑上可以看成是字典树,笔者用数组来实现字典树,具体代码如下,可作参考~
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#include<stdio.h>
#include<string.h>
#define MAX_LENTH 10
typedef struct DictionTree{
int childID[26]; //每个字母后面仅有26中可能,抽象成一种数据结构
char data[MAX_LENTH + 1]; //对应的含义
}DictionTree;
DictionTree Node[200000]; //要分配的足够多
int pNodeParent = 0;
int g_NodeCount = 1;
void init();
void createDictionTree(char*engWod, int engLenth, char*foreign, int foreignLen);
int search(char*word, int wordLen);
void init()
{
memset(Node, -1, sizeof(Node));
}
void createDictionTree(char*engWod, int engLenth, char*foreign, int foreignLen)
{
int tempParent = 0;
for (int i = 0; i < foreignLen; i++)
{
int childIndex = foreign[i] - 'a';
if (Node[tempParent].childID[childIndex] == -1)//如果说之前没有使用的话
{
Node[tempParent].childID[childIndex] = g_NodeCount;
tempParent = g_NodeCount;
g_NodeCount++;
}
else
{
tempParent = Node[tempParent].childID[childIndex];
}
}
int index;
for (index = 0; index < engLenth; index++)
{
Node[tempParent].data[index] = engWod[index];
}
Node[tempParent].data[index] = '\0';
}
int search(char*word, int wordLen)
{
int tempParent = 0;
for (int i = 0; i < wordLen; i++)
{
int childIndex = word[i] - 'a';
if (Node[tempParent].childID[childIndex] == -1)
{
return -1; //表示失败
}
else
{
tempParent = Node[tempParent].childID[childIndex];
}
}
return tempParent;
}
int main()
{
char engWord[MAX_LENTH+1];//前面的单词
char foreignMeaning[MAX_LENTH+1]; //后面的含义
char wordBeLookUp[MAX_LENTH];
freopen("input.txt", "r", stdin);
char input[2 * MAX_LENTH + 1];
init();
while (true)
{
gets(input);
if (input[0] != '\0')
{
int i;
for (i = 0; input[i] != ' '; i++)
{
engWord[i] = input[i];
}
engWord[i] = '\0';
int j;
int index = 0;
for (j = i + 1; input[j] != '\0'; j++)
{
foreignMeaning[index++] = input[j];
}
foreignMeaning[index] = '\0';
createDictionTree(engWord, i, foreignMeaning, index);
}
else
{
break;
}
}
while (true)
{
if (NULL == gets(wordBeLookUp))
{
break;
}
if (wordBeLookUp[0] != '\0')
{
int result = search(wordBeLookUp, strlen(wordBeLookUp));
if (result == -1)
{
printf("eh\n");
}
else
{
for (int j = 0; Node[result].data[j] != '\0'; j++)
{
printf("%c", Node[result].data[j]);
}
printf("\n");
}
}
else
{
break;
}
}
return 0;
}
其中输入input.txt内容如下:
dog ogday
cat atcay
pig igpay
froot ootfray
loops oopslay
aaaaa bbbbb
xxxxx yyyyy
aaaba aaaca
akghd bhaalf
atcay
ittenkay
oopslay
yyyyy