实现

  1. class Trie:
  2. def __init__(self):
  3. self.root = {"is_word": False}
  4. self.size = 0
  5. # 返回单词数量
  6. def get_size(self):
  7. return self.size
  8. # 向trie中添加一个单词
  9. def add(self, words):
  10. cur = self.root
  11. for i in words:
  12. if i not in cur:
  13. cur[i] = dict(is_word=False)
  14. self.size += 1
  15. cur = cur[i]
  16. if not cur["is_word"]:
  17. cur["is_word"] = True
  18. # 是否包含某个单词
  19. def contains(self, words):
  20. cur = self.root
  21. for i in words:
  22. if i not in cur:
  23. return False
  24. cur = cur[i]
  25. return cur["is_word"]
  26. # 查询是否存在单词已words_prefix作为前缀
  27. def is_prefix(self, words_prefix):
  28. cur = self.root
  29. for i in words_prefix:
  30. if i not in cur:
  31. return False
  32. cur = cur[i]
  33. return True