#include <stdio.h>
#include <stdlib.h>
#define KIND 26
typedef struct trie
{
int num;
struct trie* next[KIND];
}TRIE;
void init_trie(TRIE* T)
{
int i = 0;
T->num = 0;
for(; i<KIND; i++)
T->next[i] = NULL;
}
void add_trie(TRIE** T, char* word)
{
int num = 0;
int i = 0;
if(*T == NULL)
{
*T = (TRIE*)malloc(sizeof(TRIE));
init_trie(*T);
}
TRIE* location = *T;
while(word[i]!='\0')
{
num = *word-'a';
if(location->next[num]!=NULL)
(location->num)++;
else
{
TRIE* p = (TRIE*)malloc(sizeof(TRIE));
init_trie(p);
location->next[num] = p;
}
i++;
location = location->next[num];
}
}
int find_trie(TRIE* T, char* word)
{
int i = 0;
int num;
int ret = 1;
TRIE* location = T;
while(word[i]!='\0')
{
num = *word-'a ';
if(location->next[num]!=NULL)
{
i++;
location = location->next[num];
}
else
{
ret = 0;
break;
}
}
return ret;
}
int main(int argc, char *argv[])
{
TRIE* T = NULL;
int i = 0;
char* word[] = {"abcd","abd","cdd","efg","hij","hi"};
for(;i<6;i++)
add_trie(&T, word[i]);
printf("%d\n",find_trie( T, "abd"));
system("PAUSE");
return 0;
}
|