Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit d105224

Browse files
aQuaaQua
aQua
authored and
aQua
committed
676 finish
1 parent 03d519e commit d105224

File tree

1 file changed

+18
-30
lines changed

1 file changed

+18
-30
lines changed

Algorithms/0676.implement-magic-dictionary/implement-magic-dictionary.go

Lines changed: 18 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -2,56 +2,44 @@ package Problem0676
22

33
// MagicDictionary 是一个神奇的字典
44
type MagicDictionary struct {
5-
lens map[int]bool
6-
keys map[string]bool
7-
changes map[string]bool
5+
keys []string
86
}
97

10-
var replaceByte = byte('?')
11-
128
// Constructor 构建了神奇字典
139
func Constructor() MagicDictionary {
1410
return MagicDictionary{
15-
lens: make(map[int]bool, 1024),
16-
keys: make(map[string]bool, 1024),
17-
changes: make(map[string]bool, 1024),
11+
keys: make([]string, 0, 1024),
1812
}
1913
}
2014

2115
// BuildDict 往字典里面添加内容
2216
func (md *MagicDictionary) BuildDict(dict []string) {
2317
for _, w := range dict {
24-
n := len(w)
25-
md.lens[n] = true
26-
27-
bs := []byte(w)
28-
for i := 0; i < n; i++ {
29-
t := bs[i]
30-
bs[i] = replaceByte
31-
md.changes[string(bs)] = true
32-
bs[i] = t
33-
}
18+
md.keys = append(md.keys, w)
3419
}
3520
}
3621

3722
// Search returns if there is any word in the trie that equals to the given word after modifying exactly one character
3823
func (md *MagicDictionary) Search(word string) bool {
3924
n := len(word)
4025

41-
if !md.lens[n] {
42-
return false
26+
for _, w := range md.keys {
27+
if len(w) != n || w == word {
28+
continue
29+
}
30+
if isChanges(w, word) {
31+
return true
32+
}
4333
}
34+
return false
35+
}
4436

45-
bs := []byte(word)
46-
count := 0
47-
for i := 0; i < n; i++ {
48-
t := bs[i]
49-
bs[i] = replaceByte
50-
if md.changes[string(bs)] {
51-
count++
37+
func isChanges(w, word string) bool {
38+
n := len(w)
39+
for i := range w {
40+
if w[i] == word[i] {
41+
n--
5242
}
53-
bs[i] = t
5443
}
55-
56-
return count == 1 || count == n
44+
return n == 1
5745
}

0 commit comments

Comments
 (0)