AC代码
字典树
#include<iostream>
#include<stdio.h>#include<stdlib.h>
#include<string.h>
using namespace std;
typedef struct node{
char *s;//存储每个单词所对应的另一个单词
struct node *next[26];
} Node;
Node *root;
Node *newNode()//创建新节点
{Node *p;
p = (Node *)malloc(sizeof(Node));
for (int i = 0; i < 26; i++)
p->next[i] = NULL;
p->s = NULL;
return p;
}
void insert(char *str1, char *str2)//添加字符串,比如from fiwo,则把fiwo加到字典树中,而把from与之对应
{Node *p;
p = root;
for (int i = 0; i < strlen(str1); i++)
{
if (p->next[str1[i]-'a'] == NULL)
{
p->next[str1[i]-'a'] = newNode();
}
p = p->next[str1[i]-'a'];
}
p->s = new char[12];
strcpy(p->s, str2);
}
void transform(char *str)//对传进来的str字符串转化
{Node *p;
p = root;//初始时指向字典树的根节点
int flag = true;
for (int i = 0; i < strlen(str); i++)
{
if (p->next[str[i]-'a'] == NULL)//这种情况就是str中第一个字母
{ //就不在字典树中,那么直接输出即可,然后返回主程序
printf("%s", str);
return;
}
else
p = p->next[str[i]-'a'];
}
if (p->s != NULL)
printf("%s", p->s);
else if (p->s == NULL && p != root)//考虑到str中只有一个字符的情况,而这个字符恰恰在字典树中
printf("%s", str);
}
int main()
{
char s1[3005], s2[12], temp[12], ss[15];
root = newNode();
scanf("%s", temp);
while (scanf("%s %s", s1, s2))//注意当s1是END时,s2输入的值是START
{
if (s1[0] == 'E')
break;
insert(s2, s1);
}
getchar();
while (gets(s1))
{
if (s1[0] == 'E')
break;
int j = 0;
bool flag = false;
for (int i = 0; i < strlen(s1); i++)
{
if (islower(s1[i]))//是小写字母
{
ss[j++] = s1[i];
flag = true;
}
else//不是小写字母的字符
{
if (flag)
{
ss[j] = '\0';
j = 0;
flag = false;
transform(ss);
}
putchar(s1[i]);//直接输出该字符,但是得放在上面的if后面,想想为什么
}
}
if (flag)//这种情况就是考虑到如果输入的字符串全部是小写字母,那么上面的for循环里的内容就处理不了这种情况
{
ss[j] = '\0';
j = 0;
transform(ss);
}
printf("\n");
}
return 0;
}
/*
下面给出部分输入数据:
START
from fiwo
hello difh
mars riwosf
earth fnnvk
like fiiwj
END
START
difh, i'm fiwo riwosf.
i fiiwj fnnvk!
i
fiwo
d
ifiwo
END
Sample Output
hello, i'm from mars.
i like earth!
i
fiwo
d
ifiwo
*/