676.implement-magic-dictionary.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. type trie struct {
  2. word bool
  3. next [26]*trie
  4. }
  5. func (t *trie) insert(s string) {
  6. for _, r := range s {
  7. i := r - 'a'
  8. if t.next[i] == nil {
  9. t.next[i] = &trie{}
  10. }
  11. t = t.next[i]
  12. }
  13. t.word = true
  14. }
  15. func (t *trie) search(s string) *trie {
  16. res := t
  17. for _, r := range s {
  18. res = res.next[r-'a']
  19. if res == nil {
  20. break
  21. }
  22. }
  23. return res
  24. }
  25. type MagicDictionary struct {
  26. tree trie
  27. }
  28. /** Initialize your data structure here. */
  29. func Constructor() MagicDictionary {
  30. return MagicDictionary{}
  31. }
  32. /** Build a dictionary through a list of words */
  33. func (this *MagicDictionary) BuildDict(dict []string) {
  34. for _, s := range dict {
  35. this.tree.insert(s)
  36. }
  37. }
  38. /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
  39. func (this *MagicDictionary) Search(word string) bool {
  40. for i := range word {
  41. t := this.tree.search(word[:i])
  42. if t == nil {
  43. continue
  44. }
  45. for j := 0; j < 26; j++ {
  46. if j == int(word[i]-'a') || t.next[j] == nil {
  47. continue
  48. }
  49. if s := t.next[j].search(word[i+1:]); s != nil && s.word {
  50. return true
  51. }
  52. }
  53. }
  54. return false
  55. }
  56. /**
  57. * Your MagicDictionary object will be instantiated and called as such:
  58. * obj := Constructor();
  59. * obj.BuildDict(dict);
  60. * param_2 := obj.Search(word);
  61. */