// Inserts a word into the trie. voidinsert(string word){ insertToNode(word, root); }
voidinsertToNode(string word, TrieNode* node){ if (word.empty()) { node->wordEnd = true; return; } for (int i = 0; i < node->children.size(); i++) { if (word[0] == node->children[i]->val) { return insertToNode(word.substr(1), node->children[i]); } } TrieNode *p = new TrieNode(word[0], node); node->children.push_back(p); for (int i = 1; i < word.size(); i++) { TrieNode *tmp = new TrieNode(word[i], p); p->children.push_back(tmp); p = tmp; } p->wordEnd = true; }
// Returns if the word is in the trie. boolsearch(string word, TrieNode *node = nullptr){ int pos = 0; TrieNode *p = (node ? node : root); if (word.empty()) { if (p->wordEnd) returntrue; else returnfalse; } for (; pos < word.size(); pos++) { if (word[pos] == '.') { if (p->children.empty() && word.size() > 1) returnfalse; for (int i = 0; i < p->children.size(); i++) { if (search(word.substr(pos + 1), p->children[i])) returntrue; } returnfalse; } else { bool flag = false; for (int i = 0; i < p->children.size(); i++) { if (word[pos] == p->children[i]->val) { p = p->children[i]; flag = true; break; } } if (flag == false) { returnfalse; } } } 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++) { bool flag = false; for (int i = 0; i < p->children.size(); i++) { if (prefix[pos] == p->children[i]->val) { p = p->children[i]; flag = true; break; } } if (flag == false) { returnfalse; } } returntrue; }
};
classWordDictionary { public: Trie trie;
// Adds a word into the data structure. voidaddWord(string word){ trie.insert(word); }
// Returns if the word is in the data structure. A word could // contain the dot character '.' to represent any one letter. boolsearch(string word){ return trie.search(word); } };