这几天主要做了一下LintCode上有关字典树的相关题目(其实一共就3道),写个总结。
这也是我第一次接触 字典树 这种数据结构。
LintCode 442 实现Trie
基础题,实现字典树的数据结构与一些简单的函数。字典树的相关概念我觉得很好理解,具体用途可能就是避免大量重复查找吧。
class TrieNode {
public:
bool isWord;//判断是否是一个单词,比如往字典树里插入单词hello,查找单词he,返回的结果肯定是false。
int nCount;//可选,判断前缀出现的次数。比如插入hello,hell,搜寻he,返回就是2,说明有两个单词有这个前缀
TrieNode *next[26];//假定为字符a~z,所以用0~25来代表。
// Initialize your data structure here.
TrieNode() {
isWord= false;
nCount = 1;
for (int i = 0; i < 26; i++){
next[i] = NULL;
}
}
//这里写一个另一种形式的初始化,应该是针对C++11特性的
TrieNode():isWord(false),nCount(1){
for (auto &id : next) id = NULL;
}
};
class Trie {
public:
Trie() {
//字典树首先要声明一个头结点,本身没有任何意义
root = new TrieNode();
}
// Inserts a word into the trie.
void insert(string word) {
TrieNode *p = root;
for (int i = 0; i < word.size(); i++) {
int id = word[i]-'a';
if (p->next[id] == NULL) {
p->next[id] = new TrieNode();
} else {
p->next[id]->nCount++;
}
p = p->next[id];
}
p->isWord = true;
}
// Returns if the word is in the trie.
bool search(string word) {
TrieNode *p = root;
for (int i = 0; i < word.size(); i++) {
int id = word[i]-'a';
if (p->next[id] ==