@@ -2,56 +2,44 @@ package Problem0676
2
2
3
3
// MagicDictionary 是一个神奇的字典
4
4
type MagicDictionary struct {
5
- lens map [int ]bool
6
- keys map [string ]bool
7
- changes map [string ]bool
5
+ keys []string
8
6
}
9
7
10
- var replaceByte = byte ('?' )
11
-
12
8
// Constructor 构建了神奇字典
13
9
func Constructor () MagicDictionary {
14
10
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 ),
18
12
}
19
13
}
20
14
21
15
// BuildDict 往字典里面添加内容
22
16
func (md * MagicDictionary ) BuildDict (dict []string ) {
23
17
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 )
34
19
}
35
20
}
36
21
37
22
// Search returns if there is any word in the trie that equals to the given word after modifying exactly one character
38
23
func (md * MagicDictionary ) Search (word string ) bool {
39
24
n := len (word )
40
25
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
+ }
43
33
}
34
+ return false
35
+ }
44
36
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 --
52
42
}
53
- bs [i ] = t
54
43
}
55
-
56
- return count == 1 || count == n
44
+ return n == 1
57
45
}
0 commit comments