leetcode 208的代码:
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
typedef struct Trie {
struct Trie *children[26];
bool is_end;
} Trie;
Trie *
trieCreate()
{
Trie *t = malloc (sizeof (Trie));
memset (t->children, 0, sizeof (t->children));
t->is_end = false;
return t;
}
void
trieInsert (Trie *t, char *word)
{
int n = strlen (word);
for (int i = 0; i < n ; ++i) {
int ch = word[i] - 'a';
if (t->children[ch] == NULL) {
t->children[ch] = trieCreate();
}
t = t->children[ch];
}
t->is_end = true;
}
bool
trieSearch (Trie *t, char *word)
{
int n = strlen (word);
for (int i = 0; i < n; ++i) {
int ch = word[i] - 'a';
if (t->children[ch] == NULL)
return false;
t = t->children[ch];
}
return t->is_end;
}
bool
trieStartsWith (Trie *t, char *prefix)
{
int n = strlen (prefix);
for (int i = 0; i < n; ++i) {
int ch = prefix[i] - 'a';
if (t->children[ch] == NULL)
return false;
t = t->children[ch];
}
return true;
}
void
trieFree (Trie *t)
{
for (int i = 0; i < 26 ; ++i) {
if (t->children[i])
trieFree (t->children[i]);
}
free (t);
}