字典树

本文介绍了一种使用字典树(Trie)的数据结构来实现单词与其对应缩写的高效映射方法。通过构建字典树,可以快速地插入和查找单词及其对应的全称,适用于需要频繁进行单词缩写转换的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值