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

Commit 3615af3

Browse files
aQuaaQua
aQua
authored and
aQua
committed
736 尝试简化逻辑
1 parent e983546 commit 3615af3

File tree

1 file changed

+22
-7
lines changed

1 file changed

+22
-7
lines changed

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

+22-7
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import (
77
)
88

99
func evaluate(expression string) int {
10+
expression = strings.Replace(expression, "(", "( ", -1)
11+
expression = strings.Replace(expression, ")", " )", -1)
1012
m := make(map[string]int, 8)
1113
return helper(expression, m)
1214
}
@@ -20,8 +22,8 @@ func helper(exp string, m map[string]int) int {
2022
return m[exp]
2123
}
2224

23-
// 删除最外层的 "()"
24-
exp = exp[1 : len(exp)-1]
25+
// 删除最外层的 "( " 和 " )"
26+
exp = exp[2 : len(exp)-2]
2527
es := split(exp)
2628
switch es[0] {
2729
case "add":
@@ -41,17 +43,30 @@ func helper(exp string, m map[string]int) int {
4143
}
4244

4345
func split(exp string) []string {
44-
exp = strings.Replace(exp, ")", " )", -1)
4546
// TODO: 删除此处内容
4647
fmt.Println(exp)
4748
ss := strings.Split(exp, " ")
4849
leftCount := 0
4950
res := make([]string, 0, len(ss))
5051
for _, s := range ss {
51-
if leftCount == 0 {
52-
res = append(res, s)
53-
} else {
54-
res[len(res)-1] += " " + s
52+
53+
switch s {
54+
case "(":
55+
if leftCount == 0 {
56+
res = append(res, s)
57+
} else {
58+
res[len(res)-1] += " ("
59+
}
60+
leftCount++
61+
case ")":
62+
res[len(res)-1] += " )"
63+
leftCount--
64+
default:
65+
if leftCount == 0 {
66+
res = append(res, s)
67+
} else {
68+
res[len(res)-1] += " " + s
69+
}
5570
}
5671
// TODO: 删除此处内容
5772
fmt.Println(res[len(res)-1])

0 commit comments

Comments
 (0)