字典树
来源:互联网 发布:燕十八mysql 百度网盘 编辑:程序博客网 时间:2024/06/06 00:20
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<stdlib.h>
using namespace std;
struct node{
int count;
char word[30];
struct node *next[30];
node(){
count=0;
memset(next,0,sizeof(next));//初始化
}
};
struct node *h,*p,*q;
char w1[30],w2[30],s[3010];
void insert(char *s1,char *s2){
p=h;
int len=strlen(s1);
for(int i=0;i<len;i++){
if(p->next[s1[i]-'a']==NULL){
q=new node;
p->next[s1[i]-'a']=q;//新建
}
p=p->next[s1[i]-'a'];
}
p->count=1;//终点标记~
strcpy(p->word,s2);
}
char *find(char *s1){
p=h;
int len=strlen(s1);
for(int i=0;i<len;i++){
p=p->next[s1[i]-'a'];
if(p==0)
return NULL;
}//错误点:遍历完以后再查输出!
if(p->count==1)return p->word;
else return NULL;
}
int main(void){
scanf("%s",&w1);
h=new node;
while(1){
scanf("%s",&w1);
if(strcmp(w1,"END")==0)break;
scanf("%s",&w2);
insert(w2,w1);
}
scanf("%s",&w1);
getchar();
while(1){
gets(s);
if(strcmp(s,"END")==0)break;
int len=strlen(s);
for(int i=0;i<len;i++){
int m=0;
while(s[i]>='a' && s[i]<='z'){
w1[m++]=s[i];//存入一个临时字符串
i++;
}
w1[m]='\0';
char *st=find(w1);
if(st!=0)printf("%s",st);
else printf("%s",w1);
printf("%c",s[i]);
}
puts("");
}
return 0;
}
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<stdlib.h>
using namespace std;
struct node{
int count;
char word[30];
struct node *next[30];
node(){
count=0;
memset(next,0,sizeof(next));//初始化
}
};
struct node *h,*p,*q;
char w1[30],w2[30],s[3010];
void insert(char *s1,char *s2){
p=h;
int len=strlen(s1);
for(int i=0;i<len;i++){
if(p->next[s1[i]-'a']==NULL){
q=new node;
p->next[s1[i]-'a']=q;//新建
}
p=p->next[s1[i]-'a'];
}
p->count=1;//终点标记~
strcpy(p->word,s2);
}
char *find(char *s1){
p=h;
int len=strlen(s1);
for(int i=0;i<len;i++){
p=p->next[s1[i]-'a'];
if(p==0)
return NULL;
}//错误点:遍历完以后再查输出!
if(p->count==1)return p->word;
else return NULL;
}
int main(void){
scanf("%s",&w1);
h=new node;
while(1){
scanf("%s",&w1);
if(strcmp(w1,"END")==0)break;
scanf("%s",&w2);
insert(w2,w1);
}
scanf("%s",&w1);
getchar();
while(1){
gets(s);
if(strcmp(s,"END")==0)break;
int len=strlen(s);
for(int i=0;i<len;i++){
int m=0;
while(s[i]>='a' && s[i]<='z'){
w1[m++]=s[i];//存入一个临时字符串
i++;
}
w1[m]='\0';
char *st=find(w1);
if(st!=0)printf("%s",st);
else printf("%s",w1);
printf("%c",s[i]);
}
puts("");
}
return 0;
}
0 0