题目

实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。

示例:

  1. Trie trie = new Trie();
  2. trie.insert("apple");
  3. trie.search("apple"); // 返回 true
  4. trie.search("app"); // 返回 false
  5. trie.startsWith("app"); // 返回 true
  6. trie.insert("app");
  7. trie.search("app"); // 返回 true

说明:

  • 可以假设所有的输入都是由小写字母 a-z 构成的。
  • 保证所有输入均为非空字符串。

方案一(数组)

  1. class Node:
  2. def __init__(self, val):
  3. self.val = val
  4. self.is_word = False # 是否是一个词
  5. self.children = [None] * 26
  6. class Trie:
  7. def __init__(self):
  8. """
  9. Initialize your data structure here.
  10. """
  11. self.root = Node(None)
  12. def insert(self, word: str) -> None:
  13. """
  14. Inserts a word into the trie.
  15. """
  16. nodes = self.root.children
  17. length = len(word)
  18. for i, c in enumerate(word):
  19. index = ord(c) - 97 # ord('a') == 97
  20. if not nodes[index]:
  21. nodes[index] = Node(c)
  22. if i == length - 1:
  23. nodes[index].is_word = True
  24. nodes = nodes[index].children
  25. def search(self, word: str) -> bool:
  26. """
  27. Returns if the word is in the trie.
  28. """
  29. nodes = self.root.children
  30. length = len(word)
  31. for i, c in enumerate(word):
  32. index = ord(c) - 97
  33. if not nodes[index]:
  34. return False
  35. if i == length - 1:
  36. if nodes[index].is_word:
  37. return True
  38. else:
  39. return False
  40. nodes = nodes[index].children
  41. def startsWith(self, prefix: str) -> bool:
  42. """
  43. Returns if there is any word in the trie that starts with the given prefix.
  44. """
  45. nodes = self.root.children
  46. length = len(prefix)
  47. for i, c in enumerate(prefix):
  48. index = ord(c) - 97
  49. if not nodes[index]:
  50. return False
  51. if i == length - 1:
  52. return True
  53. nodes = nodes[index].children

方案二(Map)

  1. class Trie:
  2. def __init__(self):
  3. """
  4. Initialize your data structure here.
  5. 'bed' -> {
  6. 'b': {
  7. 'e': {
  8. 'd': {
  9. 'is_word': True
  10. }
  11. }
  12. }
  13. }
  14. """
  15. self.lookup = {}
  16. def insert(self, word: str) -> None:
  17. """
  18. Inserts a word into the trie.
  19. """
  20. node = self.lookup
  21. for c in word:
  22. if c not in node:
  23. node[c] = {}
  24. node = node[c]
  25. node['is_word'] = True
  26. def search(self, word: str) -> bool:
  27. """
  28. Returns if the word is in the trie.
  29. """
  30. node = self.lookup
  31. for c in word:
  32. if c not in node:
  33. return False
  34. node = node[c]
  35. # 判断是否是单词
  36. if 'is_word' in node:
  37. return True
  38. return False
  39. def startsWith(self, prefix: str) -> bool:
  40. """
  41. Returns if there is any word in the trie that starts with the given prefix.
  42. """
  43. node = self.lookup
  44. for c in prefix:
  45. if c not in node:
  46. return False
  47. node = node[c]
  48. return True

原文

https://leetcode-cn.com/explore/learn/card/trie/166/basic-operations/645/