211. Design Add and Search Words Data Structure

1. Description

Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the WordDictionary class:

  • WordDictionary() Initializes the object.
  • void addWord(word) Adds word to the data structure, it can be matched later.
  • bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots ‘.’ where dots can be matched with any letter.

2. Example

Example 1

Input
[“WordDictionary”,“addWord”,“addWord”,“addWord”,“search”,“search”,“search”,“search”]
[[],[“bad”],[“dad”],[“mad”],[“pad”],[“bad”],[".ad"],[“b.."]]
Output
[null,null,null,null,false,true,true,true]

Explanation
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord(“bad”);
wordDictionary.addWord(“dad”);
wordDictionary.addWord(“mad”);
wordDictionary.search(“pad”); // return False
wordDictionary.search(“bad”); // return True
wordDictionary.search(".ad”); // return True
wordDictionary.search(“b.."); // return True

3. Constraints

  • 1 <= word.length <= 25
  • word in addWord consists of lowercase English letters.
  • word in search consist of ‘.’ or lowercase English letters.
  • There will be at most 2 dots in word for search queries.
  • At most 10$^4$ calls will be made to addWord and search.

4. Solutions

Trie

m is the number of alphabets, n is the number of dots
Time complexity(addWor): O(m)
Time complexity(search): O(m26$^n$)
Space complexity(addWord): O(1)
Space complexity(search): O(m)

class WordDictionary {
public:
    WordDictionary() {
        root = new TrieNode();
    }

    ~WordDictionary() {
        destroy(root);
    }

    void addWord(const string &word) {
        auto iter = root;
        for (char c : word) {
            if (iter->children[index(c)] == nullptr) {
                iter->children[index(c)] = new TrieNode();
            }

            iter = iter->children[index(c)];
        }

        iter->end = true;
    }

    bool search(const string &word) {
        return search(word, 0, root);
    }

private:
    struct TrieNode {
        bool end = false;
        array<TrieNode *, 26> children{};
    };

    inline static int index(char letter) {
        return letter - 'a';
    }

    bool search(const string &word, int letter_index, TrieNode *sub_root) {
        auto iter = sub_root;
        for (int i = letter_index, n = word.size(); i < n; ++i) {
            char letter = word[i];
            if (letter == '.') {
                for (int c = 0; c < 26; ++c) {
                    if (iter->children[c] != nullptr && search(word, i + 1, iter->children[c])) {
                        return true;
                    }
                }

                return false;
            } else {
                if (iter->children[index(letter)] == nullptr) {
                    return false;
                }

                iter = iter->children[index(letter)];
            }
        }

        return iter->end;
    }

    void destroy(TrieNode *node) {
        if (node == nullptr) {
            return;
        }

        for (TrieNode *child : node->children) {
            destroy(child);
        }

        delete node;
    }

    TrieNode *root;
};
comments powered by Disqus