这题就是字典树的应用;虽然简单,但还是Runtime error 了好多次才过的,后来改了一点点东西,就不知不觉的A了。
What Are You Talking About
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define max 26
typedef struct node //字典树结点信息
{
struct node * next[max]; //26个字母的对应下标
int flag; //标记是否是一个单词结尾
char word[max]; //保存翻译后的单词
}node, * Node;
Node root; //根结点
char ss[3010]; //保存需要翻译的句子
void insert(char * str, char * sub) //建树
{
int i, index, len;
Node current, newnode;
len = strlen(str);
if(len == 0) //如果len = 0 直接跳出
return ;
current = root;
for(i = 0; i < len; i ++)
{
index = str[i] - 'a'; //该单词所在的下标
if(current->next[index] != NULL) //该字母与存在
{
current = current->next[index]; //指针移动
}
else //如果该单词还不存在,新增一个结点
{
newnode = (Node) calloc (1, sizeof(node)); //为新增结点分配空间
current->next[index] = newnode;
current = newnode;
}
}
current->flag = 1; //标记为单词结尾
strcpy(current->word, sub); //保存相应的翻译后的单词
}
void find(char * str, char * sub) //查找单词,并保存翻译后的单词
{
int i, index, len;
Node current;
len = strlen(str);
current = root;
for(i = 0; i < len; i ++)
{
index = str[i] - 'a'; //该字母所在的下标
if(current->next[index] != NULL) //如果该字母已存在
{
current = current->next[index];
}
else //如果该字母不存在,直接跳出
{
strcpy(sub, "");
return ;
}
}
if(current->flag = 1) //如果在字典树中找到了要找的单词,将该单词的译文保存在sub中返回
{
strcpy(sub, current->word);
}
else //字典树中没有该单词
{
strcpy(sub, "");
}
}
int main()
{
int i, lenth, k, a;
char str1[max], str2[max], ch[max], ch1[max];
root = (Node) calloc (1, sizeof(node)); //为根结点分配空间
gets(str1);
if(strcmp(str1, "START") == 0) //下面开始输入单词跟对应的译文
{
scanf("%s", str1);
while(strcmp(str1, "END") != 0)
{
scanf("%s", str2);
insert(str2, str1); //建树
scanf("%s", str1);
}
}
scanf("%s", str1);
getchar();
if(strcmp(str1, "START") == 0)
{
gets(ss); //输入要翻译的句子
while(strcmp(ss, "END") != 0)
{
lenth = strlen(ss);
a = 0;
for(k = 0; k < lenth; k ++)
{
if(ss[k] >= 'a' && ss[k] <= 'z')
{
ch[a ++] = ss[k];
}
else
{
ch[a] = '\0';
find(ch, ch1); //查找
if(strcmp(ch1, "") != 0)
{
printf("%s", ch1);
}
else
{
printf("%s", ch);
}
putchar(ss[k]);
a = 0;
}
}
printf("\n");
gets(ss);
}
}
return 0;
}