实现一个trie数,包括insert(插入单词)、search(搜索单词)、startsWith(检查是否包含前缀)。输入的字符串只包含小写字符(a-z)。
#include<vector>
#include<string>
#define MAX_TRIE_CHAR_NUM 26
struct TrieNode
{
TrieNode* child[MAX_TRIE_CHAR_NUM];
bool is_end;
TrieNode() : is_end(false)
{
for (int i = 0; i < MAX_TRIE_CHAR_NUM; i++)
{
child[i] = 0;
}
}
};
void get_all_word_from_trie(TrieNode* node, std::string& word, std::vector<std::string>& wordlist)
{
for (int i = 0; i < MAX_TRIE_CHAR_NUM; i++)
{
if (node->child[i])
{
word.push_back(i + 'a');
if (node->child[i]->is_end)
{
wordlist.push_back(word);
}
get_all_word_from_trie(node->child[i], word, wordlist);
word.erase(word.length() - 1, 1);
}
}
}
void preorder_trie(TrieNode* node, int layer)
{
for (int i = 0; i < MAX_TRIE_CHAR_NUM; i++)
{
if (node->child[i])
{
for (int j = 0; j < layer; j++)
{
printf("---");
}
printf("%c", i + 'a');
if (node->child[i]->is_end)
{
printf("(end)");
}
printf("\n");
preorder_trie(node->child[i], layer + 1);
}
}
}
class TrieTree
{
public:
TrieTree() {}
~TrieTree()
{
for (int i = 0; i < _node_vec.size(); i++)
{
delete _node_vec[i];
}
}
TrieNode _root;
void insert(const char* word)
{
TrieNode* ptr = &_root;
while (*word)
{
int pos = *word - 'a';
if (!ptr->child[pos])
{
ptr->child[pos] = new_node();
}
ptr = ptr->child[pos];
word++;
}
ptr->is_end = true;
}
bool search(const char* word)
{
TrieNode* ptr = &_root;
while (*word)
{
int pos = *word - 'a';
if (!ptr->child[pos])
{
return false;
}
ptr = ptr->child[pos];
word++;
}
return ptr->is_end;
}
bool startsWith(const char* prefix)
{
TrieNode* ptr = &_root;
while (*prefix)
{
int pos = *prefix - 'a';
if (!ptr->child[pos])
{
return false;
}
ptr = ptr->child[pos];
prefix++;
}
return true;
}
private:
TrieNode* new_node()
{
TrieNode* node = new TrieNode();
_node_vec.push_back(node);
return node;
}
std::vector<TrieNode*> _node_vec;
};
class Trie
{
public:
Trie() {}
~Trie() {}
void insert(std::string word)
{
_trie_tree.insert(word.c_str());
}
bool search(std::string word)
{
return _trie_tree.search(word.c_str());
}
bool startsWith(std::string prefix)
{
return _trie_tree.startsWith(prefix.c_str());
}
private:
TrieTree _trie_tree;
};
int main()
{
Trie trie;
trie.insert("abcde");
printf("%d\n", trie.search("abcde"));
printf("%d\n",trie.startsWith("abc"));
printf("%d\n",trie.startsWith("abcdef"));
printf("%d\n",trie.startsWith("abcde"));
return 0;
}
运行结果为:
1
1
0
1