Prefix tree implementation, note that it must have is_end to determine if it is the end of a word. In fact, you can directly use a vector to store, because there are only 26 letters, just convert letters to numbers.
voidinsert(string word) { TrieNode *p = root, *node; int i = 0, n = word.size(); char ch; for (i = 0; i < n; i++) { ch = word[i]; if (p->children.count(ch)) { p = p->children[ch]; if (i == n - 1) { p->is_end = true; } continue; }
node = new TrieNode; node->children = unordered_map<char, TrieNode *>(); node->data = ch; if (i == n - 1) { node->is_end = true; } else { node->is_end = false; } p->children[ch] = node; p = node; } }
boolsearch(string word) { int i, n = word.size(); char ch; TrieNode *p = root; for (i = 0; i < n; i++) { ch = word[i]; if (p->children.count(ch)) { p = p->children[ch]; continue; } returnfalse; }
return p->is_end; }
boolstartsWith(string prefix) { int i, n = prefix.size(); char ch; TrieNode *p = root; for (i = 0; i < n; i++) { ch = prefix[i]; if (p->children.count(ch)) { p = p->children[ch]; continue; } returnfalse; }
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); */
boolsearch(string word) { TrieNode *p = root; for (char ch : word) { if (p->children[ch - 'a']) p = p->children[ch - 'a']; else returnfalse; } return p->is_end; }
boolstartsWith(string prefix) { TrieNode *p = root; for (char ch : prefix) { if (p->children[ch - 'a']) p = p->children[ch - 'a']; else returnfalse; } 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); */