Trie树是一个很有价值的中级数据结构啊,花点功夫再深究一下。
模板
Trie树的实现比较特殊,每一个节点上不是一个单独的字符,而是一个映射表:
[图片缺失] 原图:https://www.edisoncgh.com/wp-content/uploads/2021/02/image-1-1024x686.png
如上图所示,每一个节点里包含当前位置字母的一个映射表,然后再有每个字母指向下一层节点。
代码
class Trie {
private:
bool isEnd;
Trie *next[26];
public:
/** Initialize your data structure here. */
Trie() {
isEnd = false;
memset(next, 0, sizeof(next));
}
/** Inserts a word into the trie. */
void insert(string word) {
Trie *node = this;
for (char ch : word) {
if (node->next[ch - 'a'] == NULL) {
node->next[ch - 'a'] = new Trie();
}
node = node->next[ch - 'a'];
}
node->isEnd = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
Trie *node = this;
for (char ch : word) {
node = node->next[ch - 'a'];
if (node == NULL) {
return false;
}
}
return node->isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Trie *node = this;
for (char ch : prefix) {
node = node->next[ch - 'a'];
if (node == NULL) {
return false;
}
}
return true;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/