// 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");