📑 题目:211. 添加与搜索单词 - 数据结构设计

🚀 本题 LeetCode 传送门

题目大意

设计一个支持以下两种操作的数据结构:void addWord(word)bool search(word)search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 “.” 可以表示任何一个字母。

解题思路

  • 设计一个 WordDictionary 的数据结构,要求具有 addWord(word)search(word) 的操作,并且具有模糊查找的功能。
  • 这一题是第 208 题的加强版,在第 208 题经典的 Trie 上加上了模糊查找的功能。其他实现一模一样。

代码

  1. package leetcode
  2. type WordDictionary struct {
  3. children map[rune]*WordDictionary
  4. isWord bool
  5. }
  6. /** Initialize your data structure here. */
  7. func Constructor211() WordDictionary {
  8. return WordDictionary{children: make(map[rune]*WordDictionary)}
  9. }
  10. /** Adds a word into the data structure. */
  11. func (this *WordDictionary) AddWord(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 := &WordDictionary{children: make(map[rune]*WordDictionary)}
  18. parent.children[ch] = newChild
  19. parent = newChild
  20. }
  21. }
  22. parent.isWord = true
  23. }
  24. /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
  25. func (this *WordDictionary) Search(word string) bool {
  26. parent := this
  27. for i, ch := range word {
  28. if rune(ch) == '.' {
  29. isMatched := false
  30. for _, v := range parent.children {
  31. if v.Search(word[i+1:]) {
  32. isMatched = true
  33. }
  34. }
  35. return isMatched
  36. } else if _, ok := parent.children[rune(ch)]; !ok {
  37. return false
  38. }
  39. parent = parent.children[rune(ch)]
  40. }
  41. return len(parent.children) == 0 || parent.isWord
  42. }
  43. /**
  44. * Your WordDictionary object will be instantiated and called as such:
  45. * obj := Constructor();
  46. * obj.AddWord(word);
  47. * param_2 := obj.Search(word);
  48. */