211.add-and-search-word-data-structure-design.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. type Node struct {
  2. IsKey bool
  3. Children *[26]Node
  4. }
  5. type WordDictionary struct {
  6. Root *Node
  7. }
  8. /** Initialize your data structure here. */
  9. func Constructor() WordDictionary {
  10. return WordDictionary{&Node{}}
  11. }
  12. /** Adds a word into the data structure. */
  13. func (this *WordDictionary) AddWord(word string) {
  14. curr := this.Root
  15. for i := range word {
  16. if curr.Children == nil {
  17. curr.Children = &[26]Node{}
  18. }
  19. curr = &curr.Children[int(word[i]-'a')]
  20. }
  21. curr.IsKey = true
  22. }
  23. /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
  24. func (this *WordDictionary) Search(word string) bool {
  25. return this.search(word, 0, this.Root)
  26. }
  27. func (this *WordDictionary) search(word string, i int, node *Node) bool {
  28. if i == len(word) {
  29. return node.IsKey
  30. } else if node.Children == nil {
  31. return false
  32. }
  33. if word[i] != '.' {
  34. return this.search(word, i+1, &node.Children[int(word[i]-'a')])
  35. }
  36. for j := 0; j < 26; j++ {
  37. if this.search(word, i+1, &node.Children[j]) {
  38. return true
  39. }
  40. }
  41. return false
  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. */