Thursday, March 5, 2020

Add and Search Word - Data structure design

Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.
Example:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
Note:
You may assume that all words are consist of lowercase letters a-z.

class TrieNode { public: TrieNode *child[26]; bool isWord; TrieNode(): isWord(false) { for (int i = 0; i < 26; i++) { child[i] = NULL; } } }; class WordDictionary { private: TrieNode *root; public: /** Initialize your data structure here. */ WordDictionary() { root = new TrieNode(); } /** Adds a word into the data structure. */ void addWord(string word) { if (word.size() == 0) { return; } TrieNode *trav = root; for (auto ch : word) { if (trav -> child[ch - 'a'] == NULL) { trav -> child[ch - 'a'] = new TrieNode(); } trav = trav -> child[ch - 'a']; } trav -> isWord = true; } /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ bool search(string word) { if (word.size() == 0) { return false; } return helper(word, root); } bool helper(string word, TrieNode *node) { if (node == NULL) { return false; } TrieNode *trav = node; for (int i = 0; i < word.size(); i++) { char ch = word[i]; if (ch != '.') { if (trav -> child[ch - 'a'] == NULL) { return false; } trav = trav -> child[ch - 'a']; } else { bool ans = false; for (auto childNode : trav -> child) { ans = helper(word.substr(i + 1), childNode); if (ans) { return ans; } } return ans; } } return trav -> isWord; } };

No comments:

Post a Comment