classTrieNode { public: char val; vector<TrieNode*> children; bool wordEnd = false; // Initialize your data structure here. TrieNode(char v = 0) : val(v){ children = vector<TrieNode*>(26, nullptr); } };
classTrie { public: Trie() { root = new TrieNode(); }
// Inserts a word into the trie. voidinsert(string word){ insertToNode(word, root); } voidinsertToNode(string word, TrieNode* node){ if(word.empty()){ node->wordEnd = true; return; } int pos; for(pos = 0; pos < word.size(); pos++){ if(node->children[word[pos] - 'a'] != nullptr){ node = node->children[word[pos] - 'a']; } else{ break; } } if(pos == word.size()) { node->wordEnd = true; return; }
for(int i = pos; i < word.size(); i++){ TrieNode *tmp = new TrieNode(word[i]); node->children[word[i] - 'a'] = tmp; node = tmp; } node->wordEnd = true; }
// Returns if the word is in the trie. boolsearch(string word){ int pos = 0; TrieNode *p = root; for(; pos < word.size(); pos++){ if(p->children[word[pos] - 'a'] != nullptr){ p = p->children[word[pos] - 'a']; } else{ break; } } if(pos == word.size() && p->wordEnd) returntrue; elsereturnfalse; }
// Returns if there is any word in the trie // that starts with the given prefix. boolstartsWith(string prefix){ int pos = 0; TrieNode *p = root; for(; pos < prefix.size(); pos++){ if(p->children[prefix[pos] - 'a'] != nullptr){ p = p->children[prefix[pos] - 'a']; } else{ break; } } if(pos == prefix.size()) returntrue; elsereturnfalse; }
private: TrieNode* root; };
// Your Trie object will be instantiated and called as such: // Trie trie; // trie.insert("somestring"); // trie.search("key");