TrieNode *searchPattern(string word) { typedef std::pair<TrieNode *, int> Match; stack<Match>s; s.push(make_pair(root, 0)); int len = word.length(); while (!s.empty()) { Match m = s.top(); TrieNode *node = m.first; s.pop(); int id = m.second; if (id >= len) { if (node->isEnd() || s.empty()) { return node; } continue; } char ch = word[m.second]; if (ch == '.') { for (int i = 0; i < TrieNode::R; i++) { if (node->links[i]) { s.push(make_pair(node->links[i], id + 1)); } } } else if (node->containsKey(ch)) { s.push(make_pair(node->get(ch), id + 1)); } } return NULL; }
// Inserts a word into the trie. void insert(string word) { TrieNode *node = root; for (int i = 0; i < word.length(); i++) { char currentChar = word[i]; if (!node->containsKey(currentChar)) { node->put(currentChar, new TrieNode()); } node = node->get(currentChar); } node->setEnd(); }
// search a prefix or whole key in trie and // returns the node where search ends TrieNode *searchPrefix(string word) { TrieNode *node = root; for (int i = 0; i < word.length(); i++) { char curLetter = word[i]; if (node->containsKey(curLetter)) { node = node->get(curLetter); } else { return NULL; } } return node; }