7. implement-trie(实现trie字典树)
链接:http://www.lintcode.com/zh-cn/problem/implement-trie/
描述:
实现一个 Trie,包含 insert
, search
, 和 startsWith
这三个方法。
注意事项
你可以假设所有的输入都是小写字母a-z。
insert("lintcode")
search("code") // return false
startsWith("lint") // return true
startsWith("linterror") // return false
insert("linterror")
search("lintcode) // return true
startsWith("linterror") // return true
分析:中等题,字典树主要有如下三点性质:
1. 根节点不包含字符,除根节点意外每个节点只包含一个字符。
2. 从根节点到某一个节点,路径上经过的字符连接起来,为该节点对应的字符串。
3. 每个节点的所有子节点包含的字符串不相同。
字母树的插入(Insert)、删除( Delete)和查找(Find)都非常简单,用一个一重循环即可,即第i次循环找到前i 个字母所对应的子树,然后进行相应的操作。实现这棵字母树,我们用最常见的数组保存(静态开辟内存)即可,当然也可以开动态的指针类型(动态开辟内存)。至于结点对儿子的指向,一般有三种方法:
1、对每个结点开一个字母集大小的数组,对应的下标是儿子所表示的字母,内容则是这个儿子对应在大数组上的位置,即标号;
2、对每个结点挂一个链表,按一定顺序记录每个儿子是谁;
3、使用左儿子右兄弟表示法记录这棵树。
三种方法,各有特点。第一种易实现,但实际的空间要求较大;第二种,较易实现,空间要求相对较小,但比较费时;第三种,空间要求最小,但相对费时且不易写。
这里使用第一种方法实现。有其他方法欢迎在讨论区交流~
对于每个节点的数据结构,需要有一个当前字符为止是否为一个字符串的标志位(isword),还要有一个字母表大小的数组。
首先来看一下insert操作,遍历需要插入的字符串,计算当前字符在字母表的位置,判断是否存在该结点,若不存在则创建结点,然后查找下一个,最后给当前结点的isword设置为true。查找(search)和查找前缀(startsWith)和insert类似,不同的是,在不存在该结点时就返回false,遍历完整个字符串,search()函数要返回到当前字符为止是否为一个字符串,startsWith()函数只需返回true即可。
/**
* Your Trie object will be instantiated andcalled as such:
* Trie trie;
* trie.insert("lintcode");
* trie.search("lint"); will returnfalse
* trie.startsWith("lint"); willreturn true
*/
class TrieNode {
public:
// Initialize your data structure here.
TrieNode *child[26];
bool isword;
TrieNode()
{
isword=false;
for(auto &it:child) //&不能去掉
it=nullptr;
}
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
void insert(string word) {
TrieNode *p=root;
for(auto &ch:word)
{
int i=ch-'a';
if(p->child[i]==nullptr)
p->child[i]=new TrieNode();
p=p->child[i];
}
p->isword=true;
}
// Returns if the word is in the trie.
bool search(string word) {
TrieNode *p=root;
for(auto &ch:word)
{
int i=ch-'a';
if(p->child[i]==nullptr)
return false;
p=p->child[i];
}
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(auto &ch:prefix)
{
int i=ch-'a';
if(p->child[i]==nullptr)
return false;
p=p->child[i];
}
return true;
}
private:
TrieNode* root;
};