问题描述:
实现一个Trie前缀树,包含insert、search和startsWith这三个操作。
问题分析:
这类的题目与堆栈的最小元素查找类似,将所有功能进行集中处理。
首先我们需要明确一下trie树的基本概念:它又称为:字典树、前缀树、单词查找树等。
其基本数据结构定义为:
与其他普通树的定义存在明显区别。最明显的差别就是Bool型变量来表征其节点是否为结束值,而TrieNode的下一个节点是指向26个字母,专门用来处理字符的。
class Trie{
private:
bool isEnd;
Trie *next[26];
public:
Trie()
{
isEnd = false;
memset(next,0,sizeof(next));
}
void insert(string word)
{
Trie *node = this;
for(char c:word)
{
if(node->next[c-'a']==NULL)
{
node->next[c-'a'] = new Trie();
}
node = node->next[c-'a'];
}
node->isEnd = true;
}
bool search(string word)
{
Trie *node = this;
for(char c:word)
{
node = node->next[c-'a'];
if(node==NULL)
{
return false;
}
}
return node->isEnd;
};
bool startsWith(string word)
{
Trie *node = this;
for(char c:word)
{
node = node->next[c-'a'];
if(node == NULL)
return false;
}
return true;
}
};