classnode { public: node *child[26]; bool isWord; node():isWord(false) { for(auto& p : child) p = nullptr; } ~node() { for(auto& p : child) delete p; } };
classTrie { public: /** Initialize your data structure here. */ Trie() { root = new node(); } ~Trie() { delete root; } /** Inserts a word into the trie. */ voidinsert(string word){ auto ptr = root; for(auto c : word) { int index = c - 'a'; if(!ptr->child[index]) ptr->child[index] = new node(); ptr = ptr->child[index]; } ptr->isWord = true; } /** Returns if the word is in the trie. */ boolsearch(string word){ auto ptr = root; for(auto c : word) { int index = c - 'a'; if(!ptr->child[index]) returnfalse; ptr = ptr->child[index]; } return ptr->isWord; } /** Returns if there is any word in the trie that starts with the given prefix. */ boolstartsWith(string prefix){ auto ptr = root; for(auto c : prefix) { int index = c - 'a'; if(!ptr->child[index]) returnfalse; ptr = ptr->child[index]; } returntrue; } private: node* root; };
classTrie { public: /** Initialize your data structure here. */ Trie() { root = new TrieNode(); } ~Trie() { delete root; } /** Inserts a word into the trie. */ voidinsert(string word){ root->build(word, 0); } /** Returns if the word is in the trie. */ boolsearch(string word){ return root->search(word, 0); } /** Returns if there is any word in the trie that starts with the given prefix. */ boolstartsWith(string prefix){ return root->prefix(prefix, 0); } private: TrieNode* root; };