天天写算法之What Are You Talking About

这个题就是一个字典树的问题,字典树翻译火星文,不难,但是我在这个题里遇到了大坑。

我才知道scanf一般不直接读入string,而是读入基本数据类型。用char*代替,而后我又遇到了getchar的问题,我还好奇为什么pe了,原来是cin或者scanf后后面继续读入char的话可能出现读入为空的情况。

解释如下 点击打开链接
代码在下:


#include <iostream>
#include <cstdio>
#include <cstring>
#include<malloc.h>
#define MAX 3111
using namespace std;

struct Node{
    string res ;
    int flag ;
    Node * next[26];
    Node(){
        for(int i = 0 ; i<26 ; i++)
        {
            next[i]=NULL;
        }
        flag = 0 ;
    }
};//字典树节点
Node *p,*root=new Node();
//插入操作
void inSert(string a , string b)
{
    p = root ;

    for(int i = 0 ; i<strlen(a.c_str()) ; i++)
    {
        int temp = a[i]-'a';
        if(p->next[temp]==NULL)
        {
            p->next[temp]= new Node();

        }
        p = p->next[temp];
    }
    p->res = b ;
    p->flag = 1 ;
}
//查找结点
string Search(string s){
    p = root;
    for(int i = 0 ; i <strlen(s.c_str());i++)
    {
        int temp = s[i]-'a';
        if(p->next[temp]==NULL)
        {
                return s;
        }
        p=p->next[temp];
    }

    if(p->flag==1)
        return p->res;
    else
        return s ;
}
    char from[MAX];
int main()
{
    string start;
    char English[MAX],Mars[MAX];
    string temp ;

    cin>>start;
    string ans;
    while(cin>>English&&strcmp(English,"END")!=0)
    {
        cin>>Mars;
        inSert(Mars,English);
    }
    cin>>start;
    getchar();//这个必须加上,不知道为什么哇
    while(gets(from)&&strcmp(from,"END")!=0)
    {
        temp= "";
        ans= "";
        for(int i = 0 ; i< strlen(from);i++)
        {

            if(from[i]<='z'&&from[i]>='a')
            {
                temp+=from[i];
            }else {
                ans+=Search(temp);
                ans+=from[i];
                temp="";
            }
        }
        cout << ans<<endl;
    }

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值