Advertisement
Byleth_CYY

Untitled

May 14th, 2020
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. class TrieNode:
  2. def __init__(self):
  3. self.children={}
  4. self.isword=False
  5.  
  6.  
  7. class WordDictionary:
  8.  
  9. def __init__(self):
  10. """
  11. Initialize your data structure here.
  12. """
  13. self.root=TrieNode()
  14.  
  15. def addWord(self, word: str) -> None:
  16. """
  17. Adds a word into the data structure.
  18. """
  19. if not word:
  20. return
  21.  
  22. node=self.root
  23. for c in word:
  24. if c not in node.children:
  25. node.children[c]=TrieNode()
  26. node=node.children[c]
  27. node.isword=True
  28.  
  29. def search_helper(self,node,word)->bool:
  30. if not node or not word:
  31. return False
  32.  
  33. for i in len(word[i]):
  34. if word[i]=='.':
  35. for child in node.children.values():
  36. if self.search_helper(child,word[i+1:]):
  37. return True
  38. else:
  39. if c not in node.children:
  40. return False
  41. node=node.children[word[i]]
  42. return node.isword
  43.  
  44. def search(self, node, word) -> bool:
  45. """
  46. Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
  47. """
  48. return self.search_helper(self.root,word)
  49.  
  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)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement