HUD1075Trie树

由huho1014的Trie练习
 
 
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
using namespace std;

struct Tire{
    Tire *next[26];
    char *trans;
    Tire()
    {
        int i;
        for(i=0;i<26;i++){
            next[i]=NULL;
        }
        trans = NULL;
    }
};

Tire root;

void Insert(char trans[],char word[])
{
    Tire *p = &root;
    int i;
    for(i=0;trans[i];i++){
        int n = trans[i]-'a';
        if(p->next[n]==NULL)
            p->next[n] = new Tire;
        p = p->next[n];
    }
    p->trans = (char*)malloc(sizeof(char)*11);
    strcpy(p->trans,word);
}
void Find(char str[])
{
    Tire *p = &root;
    int i;
    for(i=0;str[i];i++){
        int n = str[i]-'a';
        if(p->next[n]==NULL){
            printf("%s",str);
            return ;
        }
        p = p->next[n];
    }
    if(p->trans==NULL)
        printf("%s",str);
    else
        printf("%s",p->trans);
}

int main()
{
    char word[11],trans[11];
    scanf("%s",word);
    while(scanf("%s",word)!=EOF){
        if(strcmp(word,"END")==0)
            break;
        scanf("%s",trans);
        Insert(trans,word);
    }
    scanf("%s",word);
    getchar();
    char str[3001];
    while(gets(str)){
        if(strcmp(str,"END")==0)
            break;
        int i,j=0;
        char t[3001]={0};
        for(i=0;str[i];i++){
            if('a'<=str[i] && str[i]<='z'){
                t[j++] = str[i];
            }
            else{
                t[j] = '\0';
                if(t[0]!='\0'){
                    Find(t);
                    t[0]='\0',j=0;
                }
                printf("%c",str[i]);
            }
        }
        printf("\n");
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/amous_x/article/details/80073375
HUD