實現 Trie
具體地可以看這篇博客:
字典樹入門
版本1:
class Trie {
public:
/** Initialize your data structure here. */
Trie() {
root = new Node;
}
~Trie(){
queue<Node*> q;
q.push(root);
while(!q.empty()){
Node* pn = q.front();
q.pop();
for(unordered_map<char,Node*>::iterator it=pn->childs.begin(); it!=pn->childs.end();it++ ){
q.push(it->second);
}
delete pn;
pn = nullptr;
}
}
/** Inserts a word into the trie. */
void insert(string word) {
Node* p = root;
for(char c:word){
if(!p->childs.count(c)){
p->childs[c] = new Node;
}
p = p->childs[c];
}
p->isEnd = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
Node* p = root;
for(char c:word){
if(!p->childs.count(c)){
return false;
}
p = p->childs[c];
}
return p->isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Node* p = root;
for(char c:prefix){
if(!p->childs.count(c)){
return false;
}
p = p->childs[c];
}
return true;
}
private:
struct Node{
bool isEnd = false;
unordered_map<char,Node*> childs;
};
Node * root;
};
版本2:
class Trie {
public:
/** Initialize your data structure here. */
Trie() {
root = new TrieNode;
}
~Trie(){
destroy(root);
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode *p = root;
for(char c:word){
if(p->childs[c-'a'] == nullptr){
p->childs[c-'a'] = new TrieNode;
}
p = p->childs[c-'a'];
}
p->isEnd = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode *p = root;
for(char c:word){
if(p->childs[c-'a']==nullptr){
return false;
}
p = p->childs[c-'a'];
}
return p->isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode *p = root;
for(char c:prefix){
if(p->childs[c-'a']==nullptr){
return false;
}
p = p->childs[c-'a'];
}
return true;
}
private:
struct TrieNode{
bool isEnd = false;
TrieNode* childs[26] = {0};
};
TrieNode* root ;
void destroy(TrieNode* root){
if(!root){
return ;
}
for(TrieNode* pt:root->childs){
destroy(pt);
}
if(root){
delete root;
root = nullptr;
}
}
};
偷偷吐槽一句,爲什麼這麼多人寫c++只管new,不管delete呢?