leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

design-add.py (1330B)


      1 class TreeNode:
      2     def __init__(self):
      3         self.isWord = False
      4         self.chars = {}
      5 
      6 
      7 class WordDictionary:
      8 
      9     def __init__(self):
     10         self.root = TreeNode()
     11 
     12     def addWord(self, word: str) -> None:
     13         current = self.root
     14 
     15         for char in word:
     16             if char in current.chars:
     17                 current = current.chars[char]
     18             else:
     19                 node = TreeNode()
     20                 current.chars[char] = node
     21                 current = current.chars[char]
     22 
     23         current.isWord = True
     24 
     25     def search(self, word: str, root=None) -> bool:
     26 
     27         current = None
     28 
     29         if root is None:
     30             current = self.root
     31         else:
     32             current = root
     33 
     34         for index, char in enumerate(word):
     35 
     36             if char == ".":
     37                 for option in current.chars:
     38                     test = self.search(word[index + 1 :], current.chars[option])
     39                     if test:
     40                         return True
     41                 return False
     42 
     43             if char in current.chars:
     44                 current = current.chars[char]
     45                 continue
     46             else:
     47                 return False
     48 
     49         return current.isWord
     50 
     51 
     52 # Your WordDictionary object will be instantiated and called as such:
     53 # obj = WordDictionary()
     54 # obj.addWord(word)
     55 # param_2 = obj.search(word)