image.png

题解

这道题的目的是实现一个 Trie 数据结构,Trie 实现相对简单:

  1. class TrieNode {
  2. isWord: boolean;
  3. next: Map<string, TrieNode> = new Map()
  4. constructor(isWord = false) {
  5. this.isWord = isWord
  6. }
  7. }
  8. class Trie {
  9. root: TrieNode
  10. constructor() {
  11. this.root = new TrieNode()
  12. }
  13. insert(word: string): void {
  14. // 1. 遍历 word 中的每一个字符
  15. // 2. 查看字符是否已经存在于 TrieNode 中,如果不存在,则将该字符存到 Trie 中
  16. // 3. 最后一个字符标记为单词的结尾
  17. let current = this.root
  18. for(const c of word) {
  19. if (!current.next.get(c)) {
  20. current.next.set(c, new TrieNode())
  21. }
  22. current = current.next.get(c) as TrieNode
  23. }
  24. current.isWord = true
  25. }
  26. search(word: string): boolean {
  27. // 1. 遍历 word 中的每一个字符
  28. // 2. 如果某个字符不存在,则返回 false
  29. // 3. 如果已经遍历到最后一个字符,并且都存在 Trie 中,那么则判断最后一个字符是否有 isWord 的标识
  30. let current = this.root
  31. for(const c of word) {
  32. if (current.next === null) {
  33. return false
  34. }
  35. const nextTrieNode = current.next.get(c)
  36. if (!nextTrieNode) {
  37. return false
  38. }
  39. current = nextTrieNode
  40. }
  41. return current.isWord
  42. }
  43. startsWith(prefix: string): boolean {
  44. // 1. 遍历 prefix 中的每一个字符
  45. // 2. 如果某个字符不存在,直接返回 false,否则返回 true
  46. let current = this.root
  47. for(const c of prefix) {
  48. if (current.next === null) {
  49. return false
  50. }
  51. const nextTrieNode = current.next.get(c)
  52. if (!nextTrieNode) {
  53. return false
  54. }
  55. current = nextTrieNode
  56. }
  57. return true
  58. }
  59. }
  60. /**
  61. * Your Trie object will be instantiated and called as such:
  62. * var obj = new Trie()
  63. * obj.insert(word)
  64. * var param_2 = obj.search(word)
  65. * var param_3 = obj.startsWith(prefix)
  66. */