C语言实现字典树

leetcode 208的代码:

#include 
#include 
#include 

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);
}

你可能感兴趣的:(算法,数据结构,c语言,c#,开发语言)