@@ -8,33 +8,33 @@ import (
8
8
func evaluate (expression string ) int {
9
9
expression = strings .Replace (expression , "(" , "( " , - 1 )
10
10
expression = strings .Replace (expression , ")" , " )" , - 1 )
11
- m := make (map [string ]int , 8 )
12
- return helper (expression , m )
11
+ return helper (expression , nil )
13
12
}
14
13
15
- func helper (exp string , m map [ string ] int ) int {
14
+ func helper (exp string , s * scope ) int {
16
15
if exp [0 ] != '(' {
17
16
num , err := strconv .Atoi (exp )
18
17
if err == nil {
19
18
return num
20
19
}
21
- return m [ exp ]
20
+ return s . get ( exp )
22
21
}
23
22
24
23
// 删除最外层的 "( " 和 " )"
25
24
exp = exp [2 : len (exp )- 2 ]
26
25
es := split (exp )
27
26
switch es [0 ] {
28
27
case "add" :
29
- return helper (es [1 ], copy ( m )) + helper (es [2 ], copy ( m ) )
28
+ return helper (es [1 ], s ) + helper (es [2 ], s )
30
29
case "mult" :
31
- return helper (es [1 ], copy ( m )) * helper (es [2 ], copy ( m ) )
30
+ return helper (es [1 ], s ) * helper (es [2 ], s )
32
31
default :
32
+ s = newScope (s )
33
33
var i int
34
34
for i = 1 ; i < len (es )- 2 ; i += 2 {
35
- m [ es [i ]] = helper (es [i + 1 ], copy ( m ))
35
+ s . add ( es [i ], helper (es [i + 1 ], newScope ( s ) ))
36
36
}
37
- return helper (es [i ], copy ( m ) )
37
+ return helper (es [i ], s )
38
38
}
39
39
40
40
}
@@ -49,22 +49,32 @@ func split(exp string) []string {
49
49
} else {
50
50
res [len (res )- 1 ] += " " + s
51
51
}
52
-
53
52
if s == "(" {
54
53
countLeft ++
55
54
} else if s == ")" {
56
55
countLeft --
57
56
}
58
-
59
57
}
60
58
61
59
return res
62
60
}
63
61
64
- func copy (m map [string ]int ) map [string ]int {
65
- res := make (map [string ]int , len (m ))
66
- for k , v := range m {
67
- res [k ] = v
62
+ type scope struct {
63
+ parent * scope
64
+ m map [string ]int
65
+ }
66
+
67
+ func newScope (parent * scope ) * scope {
68
+ return & scope {parent : parent , m : make (map [string ]int , 8 )}
69
+ }
70
+
71
+ func (s * scope ) get (key string ) int {
72
+ if val , ok := s .m [key ]; ok {
73
+ return val
68
74
}
69
- return res
75
+ return s .parent .get (key )
76
+ }
77
+
78
+ func (s * scope ) add (key string , val int ) {
79
+ s .m [key ] = val
70
80
}
0 commit comments