// Inserts a word into the trie. void insert(string s) { if (s.empty()) return; TrieNode* p = root; int i = 0; while (i < s.size()) { TrieNode* tmp = p->findCh(s[i]); if (nullptr == tmp) { p->addChild(s[i]); ++i; p = p->getLastChild(); } else { ++i; p = tmp; } } p->isAWord(true); return; }
// Returns if the word is in the trie. bool search(string key) { if (key.empty() || " " == key) return true; TrieNode* p = root; int i = 0; while (nullptr != p && i < key.size()) { p = p->findCh(key[i++]); } if (nullptr == p) return false; else if (i == key.size() && p->isAWord()) return true; return false; }