第一步:定义节点的结构,由于只包含小写字母,Trie树节点如下:
class TrieNode{
private:
bool isWord;
TrieNode* child[26];
public:
TrieNode() {
isWord = false;
memset(child, NULL, sizeof(child));
}
~TrieNode(){
for(int i=0;i<26;i++)
if(child[i])
delete child[i];
}
};
设计好了TrieNode的数据结构,接下来具体实现
第二步:定义构造函数和析构函数
class Trie {
TrieNode* root;
public:
/** Initialize your data structure here. */
Trie() {
root=new TrieNode();
}
~Trie(){
delete root;
}
};
虽然没有析构函数也可以通过,为了防止内存泄漏,还是加上比较好
第三步:插入/添加
void insert(string word) {
TrieNode*p=root;
for(int i=0;i<(int)word.size();i++){
if(p->child[word[i]-'a']==NULL)
p->child[word[i]-'a']=new TrieNode();
p=p->child[word[i]-'a'];
}
p->isword=true;
}
遍历需要插入的string,同时指针p从root一直往下,如果对应的child为NULL,就创建一个新的TrieNode,遍历完后,在最后的那个TrieNode标记为true ,表示这个TrieNode对应的词在Trie中存在
第四步:查找
和插入的思路类似,遍历string,同时指针P从root节点一直往下,如果碰到对应字符的child[]为NULL则返回false,否则当遍历完字符串,则退出循环。最后检查isWord是否为true,如果是说明查询成功
bool search(string word) {
TrieNode *p=root;
for(int i=0;i<(int)word.size()&&p;i++){
p=p->child[word[i]-'a'];
if(p==NULL)
return false;
}
return p->isWord;
}
第五步:前缀查找
和查找的思路一样
bool startsWith(string prefix) {
TrieNode*p=root;
for (int i=0;i<prefix.size();i++)
{
char c=prefix[i];
p = p->child[c-'a'];
if (p == NULL) {
return false;
}
}
return true;
}
完整的代码如下:
class TrieNode{
public:
bool isWord;
TrieNode* child[26];//如果将isWord和TrieNode设为Private,则类Trie无法访问
TrieNode() {
isWord = false;
memset(child, 0, sizeof(child));
}
~TrieNode(){
for(int i=0;i<26;i++)
if(child[i])
delete child[i];
}
};
class Trie {
TrieNode* root;
public:
/** Initialize your data structure here. */
Trie() {
root=new TrieNode();
}
/** Inserts a word into the Trie. */
void insert(string word) {
TrieNode*p=root;
for(int i=0;i<(int)word.size();i++){
if(p->child[word[i]-'a']==NULL)
p->child[word[i]-'a']=new TrieNode();
p=p->child[word[i]-'a'];
}
p->isWord=true;
}
/** Returns if the word is in the Trie. */
bool search(string word) {
TrieNode *p=root;
for(int i=0;i<(int)word.size()&&p;i++){
p=p->child[word[i]-'a'];
if(p==NULL)
return false;
}
return p->isWord;
}
/** Returns if there is any word in the Trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode*p=root;
for(int i=0;i<(int)prefix.size()&&p;i++){
p=p->child[prefix[i]-'a'];
if(p==NULL)
return false;
}
return true;
}
~Trie(){
delete root;
}
};