classTrie{public:/** Initialize your data structure here. */
vector<Trie*> children;bool isEnd;//三刷后 系统学习完c++补充//这种不在初始化列表初始化的习惯 相当糟糕Trie(){children = vector<Trie*>(26,nullptr); isEnd =false;}/** Inserts a word into the trie. */voidinsert(string word){
Trie* temp =this;for(constchar& chr:word){if(temp->children[chr-'a']==nullptr)
temp->children[chr-'a']=newTrie();
temp = temp->children[chr-'a'];}
temp->isEnd =true;}/** Returns if the word is in the trie. */boolsearch(string word){auto temp =this;for(constauto& chr:word){if(temp->children[chr-'a']==nullptr)returnfalse;
temp = temp->children[chr-'a'];}if(temp->isEnd)returntrue;elsereturnfalse;}/** Returns if there is any word in the trie that starts with the given prefix. */boolstartsWith(string prefix){auto temp =this;for(constauto& chr:prefix){if(temp->children[chr-'a']==nullptr)returnfalse;
temp = temp->children[chr-'a'];}returntrue;}};/**
* 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);
*/
代码实现(二刷自解 DAY 144 C++)
classTrie{public:
vector<Trie*> trie_tree;bool isend;Trie():trie_tree(26,nullptr),isend(false){}voidinsert(string word){int size = word.size();auto ptr =this;for(int i =0;i < size;++i){auto chr = word[i];if(!ptr->trie_tree[chr -'a'])
ptr->trie_tree[chr -'a']=newTrie();
ptr = ptr->trie_tree[chr -'a'];}
ptr->isend =true;}boolsearch(string word)const{auto ptr =this;for(constauto& chr:word){if(!ptr->trie_tree[chr -'a'])returnfalse;
ptr = ptr->trie_tree[chr -'a'];}return ptr->isend;}boolstartsWith(string prefix)const{auto ptr =this;for(constauto& chr:prefix){if(!ptr->trie_tree[chr -'a'])returnfalse;
ptr = ptr->trie_tree[chr -'a'];}returntrue;}};/**
* 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);
*/
Leetcode 208. 实现 Trie (前缀树)(DAY 86) ---- Leetcode Hot 100
原题题目代码实现(首学前缀树)class Trie {public: /** Initialize your data structure here. */ vector<Trie*> children; bool isEnd; Trie() {children = vector<Trie*>(26,nullptr); isEnd = false;} /** Inserts a word into the trie. */