211. 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 WordDictionary {
public:
    class TrieNode {
    public:
        bool isWord;
        vector<TrieNode*> next;
        TrieNode() : isWord(false), next(vector<TrieNode*>(26, nullptr)) {}
        ~TrieNode() {
            for (TrieNode*& ptr : next) {
                if (ptr) delete ptr;
            }
        }
    };
    /** Initialize your data structure here. */
    WordDictionary() {
        root = new TrieNode();
    }
    
    ~WordDictionary() {
        delete root;
    }
    
    /** Adds a word into the data structure. */
    void addWord(string word) {
        TrieNode* cur = root;
        for (char ch : word) {
            if (!cur->next[ch - 'a']) {
                cur->next[ch - 'a'] = new TrieNode();
            }
            cur = cur->next[ch - 'a'];
        }
        cur->isWord = true;
    }
    
    // Recursive helper function for searching words
    bool searchWord(TrieNode* p, const string& word, int idx) {
        if (idx == word.length()) return p->isWord;
        if (word[idx] == '.') {
            for (TrieNode*& child : p->next) {
                if (child && searchWord(child, word, idx + 1))
                    return true;
            }
            return false;
        } else {
            return p->next[word[idx] - 'a'] != nullptr && searchWord(p->next[word[idx] - 'a'], word, idx + 1);
        }
    }
    
    /** 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) {
        return searchWord(root, word, 0);
    }
private:
    TrieNode* root;
};

Last updated

Was this helpful?