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.
class WordDictionary(object):
 
    def __init__(self):
        self.trie = {}        
 
    def addWord(self, word):
        """
        :type word: str
        :rtype: None
        """
        if not word:
            return
        pointer = self.trie
        for c in word:
            if not c in pointer:
                pointer[c] = {}
            pointer = pointer[c]
        pointer["$"] = True
 
    def search(self, word):
        """
        :type word: str
        :rtype: bool
        """
        def search_node(word, node):
            for i, ch in enumerate(word):
                if ch in node:
                    node = node[ch]
                else:
                    if ch == '.':
                        for x in node:
                            if x != '$' and search_node(word[i+1:], node[x]):
                                return True
                    return False
            return '$' in node
        return search_node(word, self.trie)