C - Hat’s Words
A hat’s word is a word in the dictionary that is the concatenation of exactly two other words in the dictionary.
You are to find all the hat’s words in a dictionary.
You are to find all the hat’s words in a dictionary.
Input Standard input consists of a number of lowercase words, one per line, in alphabetical order. There will be no more than 50,000 words.
Only one case.
Output Your output should contain all the hat’s words, one per line, in alphabetical order. Sample Input
a ahat hat hatword hziee wordSample Output
ahat hatword
代码:
#include<iostream>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include<algorithm>
using namespace std;
const int MAX=26;
typedef struct Trie_Node
{
bool isWord;
struct Trie_Node *next[MAX];
Trie_Node()
{
isWord = false;
memset(next,0,sizeof(next));
}
}Trie;
char s[50010][50];
void insert(Trie *root,char *word)
{
Trie *p=root;
int i=0;
while(word[i]!='\0')
{
int j = word[i]-'a';
if(p->next[j]==NULL)
{
Trie *temp=new Trie();
p->next[j]=temp;
}
p=p->next[j];
i++;
}
p->isWord=true;
}
bool search(Trie *root,char *word)
{
Trie *p=root;
for(int i=0;word[i]!='\0';i++)
{
if(p->next[word[i]-'a']==NULL)
return false;
p=p->next[word[i]-'a'];
}
return p->isWord;
}
void del(Trie *root)
{
for(int i=0;i<MAX;i++)
{
if(root->next[i]!=NULL)
del(root->next[i]);
}
free(root);
}
int main()
{
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
int i,j,cnt=0;
char str[50];
Trie *root=new Trie;
while(scanf("%s",s[cnt])!=EOF)
insert(root,s[cnt++]);
for(i=0;i<cnt;i++)
{
int len=strlen(s[i]);
for(j=1;j<len-1;j++)
{
char temp1[50]={'\0'};
char temp2[50]={'\0'};
strncpy(temp1,s[i],j);
strncpy(temp2,s[i]+j,len-j);
// cout<<temp1<<endl;
// cout<<temp2<<endl;
if(search(root,temp1)&&search(root,temp2))
{
printf("%s\n",s[i]);
break;
}
}
}
del(root);
return 0;
}