Advertisement
Byleth_CYY

Untitled

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