字典樹簡單題~~~
在每個火星文的最後一個節點放上英文單詞,然後searc時返回即可!
這道題我不大理解的是一些關於char型指針和char型數組的,讓我作者道題的時候糾結了!
有些代碼和變量其實沒必要寫的,但是因爲上面那個,所以寫的麻煩了很多!
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
struct trie
{
char eng[20];
int len;
trie* next[26];
};
void inst(trie* root,char mars[],char engl[])
{
trie *p = root;
int i = 0;
while(mars[i]!='\0')
{
int k = mars[i]-'a';
if(p->next[k] == NULL)
{
trie* tmp = new trie;
for(int j = 0;j < 26;j ++)
tmp->next[j] = NULL;
tmp->len = 0;
if(mars[i+1]=='\0') {int j;for(j = 0;j < strlen(engl);j ++)tmp->eng[j] = engl[j];tmp->eng[j]='\0'; tmp->len = 1;}
p->next[k] = tmp;
}
p = p->next[k];
i ++;
}
}
char* search(trie* root, char mars[])
{
trie *p = root;
int i = 0;
while(mars[i]!='\0')
{
int k = mars[i] - 'a';
if(p->next[k] == NULL) return NULL;
else p = p->next[k];
i ++;
}
if(p->len == 0) return NULL;
return p->eng;
}
int main()
{
char mars[20],engl[20],words[3010],ques[20],*ans;
trie *root = new trie;
int i,j;
for(i = 0;i < 26;i ++) root->next[i] = NULL;
root->len = 0;
while(scanf("%s",&engl))
{
if(strcmp(engl,"START")==0) continue;
if(strcmp(engl,"END")==0) break;
scanf("%s",&mars);
inst(root,mars,engl);
}
getchar();
while(gets(words))
{
if(strcmp(words,"START")==0) continue;
if(strcmp(words,"END")==0) break;
int len = strlen(words);
j = 0;
//cout<<words<<endl;
for(i =0 ;i < len;i ++)
{
if(words[i]>='a'&&words[i]<='z') ques[j++] = words[i];
else
{
if(j > 0){
ques[j] = '\0';
ans = search(root,ques);
if(ans != NULL) {printf("%s",ans);}
else printf("%s",ques);
}
cout<<words[i];
j = 0;
}
}
printf("\n");
}
}