You are to find all the hat’s words in a dictionary.
Only one case.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define MAXNUM 26
using namespace std;
char words[50005][100];
typedef struct Trie
{
bool flag;
Trie *next[MAXNUM];
}Trie;
Trie *root;
void init()
{
root = (Trie *)malloc(sizeof(Trie));
root->flag = false;
for (int i = 0;i<MAXNUM;i++)
root->next[i] = NULL;
}
void insert(char *word)
{
Trie *tem = root;
while (*word != '\0')
{
if (tem->next[*word - 'a'] == NULL)
{
Trie *cur = (Trie *)malloc(sizeof(Trie));
for (int i = 0;i<MAXNUM;i++)
cur->next[i] = NULL;
cur->flag = false;
tem->next[*word - 'a'] = cur;
}
tem = tem->next[*word - 'a'];
word++;
}
tem->flag = true;
}
bool search(char *word)
{
Trie *tem = root;
for (int i = 0;word[i] != '\0';i++)
{
if (tem == NULL || tem->next[word[i] - 'a'] == NULL)
return false;
tem = tem->next[word[i] - 'a'];
}
return tem->flag;
}
int main()
{
init();
int t = 0;
char w[100];
while (scanf("%s", words[t]) != EOF)
{
insert(words[t]);
t++;
}
for (int i = 0;i<t;i++)
{
memset(w, '\0', sizeof(w));
for (int j = 0;words[i][j] != '\0';j++)
{
*(w + j) = *(words[i] + j);
if (search(w) && search((words[i] + j + 1)))
{
printf("%s\n", words[i]);
break;
}
}
}
return 0;
}