一、map
输入时候的格式有点难想,还有一种想法是用gets读取,然后用sscanf分开,分别存到两个数组中去,再加入map中,但是这一种方法目前还没有实现。。
#include <iostream>
#include <cstring>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
int main ()
{
string s1,s2;
char a[1000],b[1000];
char t;
map<string,string> m;
while(true)
{
int i=0;
t=getchar();
if(t=='\n')
break;
else
{
a[i++]=t;
while(true)
{
if((t=getchar())==' ')
{
a[i]='\0';
break;
}
else
a[i++]=t;
}
scanf("%s",b);
getchar();
m[b]=a;
}
}
char c[1000];
map<string,string>::iterator it;
while(scanf("%s",c)!=EOF)
{
it=m.find(c);
if(it!=m.end())
cout << m[c] << endl;
else
cout << "eh\n";
}
return 0;
}
二、链表
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
typedef struct node
{
char *str;
node *next[26];
node()
{
str = NULL;
for(int i=0;i<26;i++)
next[i] = NULL;
}
}N ;
N *root;
void insert(char *word,char *trans)
{
N *p=root;
for(int i=0;word[i];i++)
{
int x = word[i] - 'a';
if(p->next[x]==NULL)
p->next[x] = new N;
p=p->next[x];
}
p->str = new char[12];
strcpy(p->str,trans);
}
void find(char *word)
{
N *p=root;
for(int i=0;word[i];i++)
{
int x = word[i]-'a';
if(p->next[x]==NULL)
{
printf("eh\n");
return ;
}
p=p->next[x];
}
if(p->str!=NULL)
printf("%s\n",p->str);
else
printf("eh\n");
}
void del_node(N *root)
{
for(int i=0;i<26;i++)
{
if(root->next[i]!=NULL)
del_node(root->next[i]);
}
delete(root);
}
int main ()
{
char s[25],word[12],trans[12];
root = new N;
while(gets(s))
{
if(s[0]=='\0')
break;
sscanf(s,"%s%s",trans,word);
insert(word,trans);
}
while(scanf("%s",s)!=EOF)
find(s);
del_node(root);
return 0;
}