这一题和1251都是字典树,题意是给出单词以及单词的翻译,最后让你用这些单词翻译给出来的语句。
我的思路是,在每一个flag为true的单词保存对应的翻译,当翻译句子时,搜索字典树,当找到该单词、flag为true、并且该单词已经结束(很重要),就输出对应的翻译,否则,输出原来的单词。
以下是实现代码:
#include <iostream>
using namespace std;
char str[3000 + 50];
typedef struct Node
{
Node *child[26];
int n;
bool flag;
char str[15];
}Node;
void Insert (Node *root, char *str,char *ch)
{
int len = strlen (str);
Node *ans = root;
for (int i =0; i < len; i ++)
{
if (ans->child[str[i] - 'a'] == NULL)
{
Node *NewNode = (Node *) malloc (sizeof (Node));
NewNode->n = 1;
NewNode->flag = false;
for (int j = 0; j < 26; j++)
{
NewNode->child[j] = NULL;
}
ans->child[str[i] - 'a'] = NewNode;
ans = NewNode;
}
else
{
ans = ans->child[str[i] - 'a'];
ans->n ++;
}
}
ans->flag = true;
strcpy (ans->str,ch);
}
bool Search (Node *root, char *str,char *ch)
{
int len = strlen (str);
Node *ans = root;
int i;
for (i = 0; i < len; i ++)
{
if (ans->child[str[i] - 'a'] != NULL)
{
ans = ans->child[str[i] - 'a'];
}
else
{
break;
}
}
if (ans->flag == true && i == len)//i==len这个条件不能少
{
strcpy (ch, ans->str);
return true;
}
return false;
}
int main ()
{
Node *root = (Node *)malloc (sizeof (Node));
for (int i = 0; i < 26; i ++)
{
root->child[i] = NULL;
}
root->n = 0;
char ch1[15],ch2[15];
while (1)
{
scanf ("%s",ch1);
if (strcmp (ch1, "START") == 0)
{
continue;
}
else if (strcmp (ch1, "END") == 0)
{
break;
}
scanf("%s",ch2);
Insert (root, ch2, ch1);
}
getchar();
while (1)
{
gets (str);
if (strcmp (str, "START") == 0)
{
continue;
}
else if (strcmp (str, "END") == 0)
{
break;
}
char ch3[15];
int cnt = 0;
for (int i = 0; i < strlen (str); i++)
{
if (!(str[i] >= 'a' && str[i] <= 'z'))
{
ch3[cnt] = 0;
cnt = 0;
char rech[15];
if (Search (root, ch3, rech))
{
cout<<rech<<str[i];
}
else
{
cout<<ch3<<str[i];
}
}
else
{
ch3[cnt ++] = str[i];
}
}
cout<<endl;
}
}
/*
START
from fiwo
hello difh
mars riwosf
earth fnnvk
like fiiwj
END
START
difhi, i'm fiwo riwosf.
i fiiwj fnnvk!
END
*/