hdu 1075 字典树

本文介绍了一种使用字典树(Trie)的数据结构来高效实现文本中关键词的查找与替换的方法。通过构建字典树,可以快速查找并替换文本中的指定词汇,适用于大量文本处理场景。
#include<stdio.h>
#include<iostream>
struct node {
int num,i;
node *a[27];
char s[20];//定义局部不是空的
node() {
num=0;
for(i=0;i<26;i++)
a[i]=NULL;
}
}*root;
char s2[20],str[20],str1[3100],s1[20],h[20];
void insert(int len ,node *root) {
int i;
for(i=0;i<len;i++) {
if(root->a[s1[i]-'a']==NULL) 
root->a[s1[i]-'a']=new node();
root=root->a[s1[i]-'a'];
}
root->num=1;
     strcpy(root->s,s2);
return ;
}
void find (int len,node *root) {
int i;
for(i=0;i<len;i++) {
root=root->a[str[i]-'a'];
if(root==NULL)
            return ;
}
if(root->num==1)//必须判断是否存在
strcpy(h,root->s);
return;
}
void del(node *root) {
int i;
for(i=0;i<26;i++)
if(root->a[i]!=NULL)
del(root->a[i]);
delete root;
}
int main() {
int i,k;
root=new node();
        scanf("%s",str);
while(scanf("%s",s2),strcmp(s2,"END")) {
scanf("%s",s1);
insert(strlen(s1),root);
}
     scanf("%s",str);
getchar();
while(gets(str1),strcmp(str1,"END")) {
k=0;h[0]=0;
for(i=0;str1[i];i++) {
if(str1[i]>='a'&&str1[i]<='z')
str[k++]=str1[i];
else {
if(k==0) {
printf("%c",str1[i]);
continue;
}
str[k]=0;
find(strlen(str),root);
if(strlen(h)==0)
printf("%s",str);
else
printf("%s",h);
k=0;
h[0]=0;
printf("%c",str1[i]);
}
}
str[k]=0;
find(strlen(str),root);
if(strlen(h)==0)
printf("%s",str);
else
printf("%s",h);
printf("\n");
}
del(root);
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值