682. 棒球比赛

棒球比赛

解法一: 栈

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
func calPoints(operations []string) int {
stack := []int{}
ans := 0
for _, operation := range operations {
switch operation {
case "+":
stack = append(stack, stack[len(stack)-2]+stack[len(stack)-1])
ans += stack[len(stack)-1]
case "D":
stack = append(stack, stack[len(stack)-1]<<1)
ans += stack[len(stack)-1]
case "C":
ans -= stack[len(stack)-1]
stack = stack[:len(stack)-1]
default:
num, _ := strconv.Atoi(operation)
stack = append(stack, num)
ans += num
}
}
return ans
}
作者

wuhunyu

发布于

2024-07-29

更新于

2025-01-15

许可协议