# https://leetcode.com/problems/add-and-search-word-data-structure-design/
    
# Design a data structure that supports the following two operations:
#     1. void addWord(word)
#     2. 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:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.trie = {}
        

    def addWord(self, word: str) -> None:
        """
        Adds a word into the data structure.
        """
        node = self.trie
        for ch in word:
            if ch not in node:
                node[ch] = dict()
            node = node[ch]
                
        node['#'] = True

        
    def search(self, word: str) -> bool:
        """
        Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
        """
        return self.search_in_trie(self.trie, word)
    
    def search_in_trie(self, node, word) -> bool:
        if word == "":
            if '#' in node:
                return True
        elif word[0] == '.':
            for value in node.values():
                if value != True and self.search_in_trie(value, word[1:]):
                    return True
        elif word[0] in node:
            return self.search_in_trie(node[word[0]], word[1:])
        
        return False
        


# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)