题目名称
208. Implement Trie (Prefix Tree)
描述
Implement a trie with insert, search, and startsWith methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z.
分析
字典树(Trie),又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。
题目中要求我们实现三个函数:insert, search, and startsWith,并且所有的输入都是有小写字母组成的字符串。至于Trie树的实现,可以用数组,也可以用指针动态分配,考虑到小写字母共有26个,就用了数组,静态分配空间。
结点的数据结构如下:
class TrieNode {
public:
//存放指向下一个字符的指针数组
vector<TrieNode*> next;
//标记该节点是否为一个字符串的结尾
bool is_end;
//constructor,初始化next的大小为26,is_end为false
TrieNode():next(26),is_end(false){}
};
C++代码
class TrieNode {
public:
// Initialize your data structure here.
vector<TrieNode*> next;
bool is_end;
TrieNode():next(26),is_end(false){}
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
void insert(string word) {
TrieNode *p = root;
int k = 0;
for(int i=0;i<word.size();++i) {
k = word[i]-'a';
if(p->next[k] == NULL){
p->next[k] = new TrieNode();
}
p = p->next[k];
}
p->is_end = true;
}
// Returns if the word is in the trie.
bool search(string word) {
TrieNode *p = find(word);
return p!=NULL && p->is_end;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
return find(prefix) != NULL;
}
private:
TrieNode* root;
TrieNode* find(string key)
{
TrieNode *p = root;
for(int i = 0; i < key.size() && p != NULL; ++ i)
p = p -> next[key[i] - 'a'];
return p;
}
};
总结
这里只是字典树的一个小的应用,其他的功能我会在接下来的文章中给大家分享。