复习种Trie树了
最后那个句子分割的时候不好弄,其他的基本就是模板了
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int CHILD_NUM = 26;
const int BASE = 'a';
struct Node
{
Node * child[CHILD_NUM];
char * str;
Node()
{
memset(child,0,sizeof(child));
str = 0;
}
~Node()
{
for(int i = 0; i < CHILD_NUM; i++)
if(child[i])
delete child[i];
if(str)
delete []str;//对于基本类型,写不写一样
}
};
struct Trie
{
Node * root;
Trie()
{
root = new Node();
}
~Trie()
{
if(root)
delete root;
}
void Insert(char * str,char* content)
{
int len = strlen(content);
Node * cur = root;
int i = 0;
while(str[i])
{
const int &index = str[i] - BASE;
if(cur->child[index]==NULL)
cur->child[index] = new Node();
cur = cur->child[index];
i++;
}
cur->str = new char[len+1];
strcpy(cur->str,content);
}
char * Search(char * str)//返回与str匹配的字符串,没有返回0
{
Node * cur = root;
int i = 0;
while(str[i])
{
//cout << "str[i] = " << str[i] << endl;
const int& index = str[i] - BASE;
if(cur->child[index])
cur = cur->child[index];
else
return NULL;
i++;
}
return cur->str;
}
};
char str[3010];
int main()
{
char word1[15],word2[15];
scanf("%s",&word1);
Trie tree;
while(~scanf("%s%s",word1,word2)&& strcmp(word1,"END")!=0)
{
tree.Insert(word2,word1);
}
//START已被读过
getchar();//读取换行符
char tmp[50];
int cnt;
char * res;
while(gets(str) && strcmp(str,"END")!=0)
{
//cout << "str = " << str << endl;
int i = 0;
cnt = 0;
while(str[i])
{
if(islower(str[i]))
{
tmp[cnt++] = str[i];
}
else
{
if(cnt > 0)
{
tmp[cnt++] = '\0';
cnt = 0;
res = tree.Search(tmp);
if(res)
printf("%s",res);
else
printf("%s",tmp);
}
putchar(str[i]);
}
i++;
}
putchar('\n');
}
return 0;
}