Add and Search Word

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.

Solution: Trie

  • We can use trie to store and search for each word
  • To search pattern lik "..a", we need to do a dfs
class WordDictionary {
public:
    class TrieNode {
    public:
        TrieNode() : isWord(false) {};
        unordered_map<char, TrieNode*> child;
        bool isWord;
    };

    /** Initialize your data structure here. */
    WordDictionary() {
        root = new TrieNode();
    }

    /** Adds a word into the data structure. */
    void addWord(string word) {
        insert(word);
    }

    /** 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 findWord(root, 0, word);
    }

    void insert(string word) {
        TrieNode *cur = root;
        for (auto ch: word) {
            if (!cur->child[ch]) {
                cur->child[ch] = new TrieNode();
            } 
            cur = cur->child[ch];
        }
        cur->isWord = true;
    }

    bool findWord(TrieNode *node, int i, string &prefix) {
        if (i == prefix.size()) return node->isWord;

        if (prefix[i] == '.') {
            for (auto it : node->child) {
                if (findWord(it.second, i+1, prefix)) return true;
            }
            return false;
        } else {
            TrieNode *next = node->child[prefix[i]];
            if (!next) return false;
            return findWord(next, i+1, prefix);
        }
    }

private:
    TrieNode *root;
};

results matching ""

    No results matching ""