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

Commit a5a6a43

Browse files
aQuaaQua
aQua
authored and
aQua
committed
736 还是太慢了,我感觉主要的耗时在 split 上
1 parent 7bcf1d4 commit a5a6a43

File tree

1 file changed

+25
-15
lines changed

1 file changed

+25
-15
lines changed

Algorithms/0736.parse-lisp-expression/parse-lisp-expression.go

+25-15
Original file line numberDiff line numberDiff line change
@@ -8,33 +8,33 @@ import (
88
func evaluate(expression string) int {
99
expression = strings.Replace(expression, "(", "( ", -1)
1010
expression = strings.Replace(expression, ")", " )", -1)
11-
m := make(map[string]int, 8)
12-
return helper(expression, m)
11+
return helper(expression, nil)
1312
}
1413

15-
func helper(exp string, m map[string]int) int {
14+
func helper(exp string, s *scope) int {
1615
if exp[0] != '(' {
1716
num, err := strconv.Atoi(exp)
1817
if err == nil {
1918
return num
2019
}
21-
return m[exp]
20+
return s.get(exp)
2221
}
2322

2423
// 删除最外层的 "( " 和 " )"
2524
exp = exp[2 : len(exp)-2]
2625
es := split(exp)
2726
switch es[0] {
2827
case "add":
29-
return helper(es[1], copy(m)) + helper(es[2], copy(m))
28+
return helper(es[1], s) + helper(es[2], s)
3029
case "mult":
31-
return helper(es[1], copy(m)) * helper(es[2], copy(m))
30+
return helper(es[1], s) * helper(es[2], s)
3231
default:
32+
s = newScope(s)
3333
var i int
3434
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)))
3636
}
37-
return helper(es[i], copy(m))
37+
return helper(es[i], s)
3838
}
3939

4040
}
@@ -49,22 +49,32 @@ func split(exp string) []string {
4949
} else {
5050
res[len(res)-1] += " " + s
5151
}
52-
5352
if s == "(" {
5453
countLeft++
5554
} else if s == ")" {
5655
countLeft--
5756
}
58-
5957
}
6058

6159
return res
6260
}
6361

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
6874
}
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
7080
}

0 commit comments

Comments
 (0)