Advertisement
Guest User

Untitled

a guest
Feb 20th, 2020
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. class Trie:
  2.  
  3. def __init__(self):
  4. self.leaf_word = None
  5. self.children = {}
  6. """
  7. Initialize your data structure here.
  8. """
  9.  
  10.  
  11. def insert(self, word: str) -> None:
  12. curr_node = self
  13. for char in word:
  14. if char not in curr_node.children:
  15. curr_node.children[char] = Trie()
  16. curr_node = curr_node.children[char]
  17. curr_node.leaf_word = word
  18.  
  19.  
  20. def search(self, word: str) -> bool:
  21. curr_node = self
  22. for char in word:
  23. if char not in curr_node.children:
  24. return False
  25. curr_node = curr_node.children[char]
  26. return curr_node.leaf_word == word
  27.  
  28.  
  29. def startsWith(self, prefix: str) -> bool:
  30. """
  31. Returns if there is any word in the trie that starts with the given prefix.
  32. """
  33. curr_node = self
  34. for char in prefix:
  35. if char not in curr_node.children:
  36. return False
  37. curr_node = curr_node.children[char]
  38. return True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement