📑 题目:208. 实现 Trie (前缀树)

中等 🕓 2021-09-08 📈 频次: 15

**

🚀 本题 LeetCode 传送门

题目大意

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

解题思路

  • 要求实现一个 Trie 的数据结构,具有 insert, search, startsWith 三种操作
  • 这一题就是经典的 Trie 实现。本题的实现可以作为 Trie 的模板。

代码

  1. package leetcode
  2. type Trie struct {
  3. isWord bool
  4. children map[rune]*Trie
  5. }
  6. /** Initialize your data structure here. */
  7. func Constructor208() Trie {
  8. return Trie{isWord: false, children: make(map[rune]*Trie)}
  9. }
  10. /** Inserts a word into the trie. */
  11. func (this *Trie) Insert(word string) {
  12. parent := this
  13. for _, ch := range word {
  14. if child, ok := parent.children[ch]; ok {
  15. parent = child
  16. } else {
  17. newChild := &Trie{children: make(map[rune]*Trie)}
  18. parent.children[ch] = newChild
  19. parent = newChild
  20. }
  21. }
  22. parent.isWord = true
  23. }
  24. /** Returns if the word is in the trie. */
  25. func (this *Trie) Search(word string) bool {
  26. parent := this
  27. for _, ch := range word {
  28. if child, ok := parent.children[ch]; ok {
  29. parent = child
  30. continue
  31. }
  32. return false
  33. }
  34. return parent.isWord
  35. }
  36. /** Returns if there is any word in the trie that starts with the given prefix. */
  37. func (this *Trie) StartsWith(prefix string) bool {
  38. parent := this
  39. for _, ch := range prefix {
  40. if child, ok := parent.children[ch]; ok {
  41. parent = child
  42. continue
  43. }
  44. return false
  45. }
  46. return true
  47. }
  48. /**
  49. * Your Trie object will be instantiated and called as such:
  50. * obj := Constructor();
  51. * obj.Insert(word);
  52. * param_2 := obj.Search(word);
  53. * param_3 := obj.StartsWith(prefix);
  54. */