LeetCode 224. 基本计算器
题目描述
思路分析
思路描述
参考代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
func calculate(s string) int {
stack := make([]int, 0)
num := 0
sign := 1
result := 0
for i := 0; i < len(s); i++ {
if isDigit(s[i]) {
num = num*10 + int(s[i]-'0')
} else if s[i] == '+' {
result += sign * num
num = 0
sign = 1
} else if s[i] == '-' {
result += sign * num
num = 0
sign = -1
} else if s[i] == '(' {
stack = append(stack, result)
stack = append(stack, sign)
result = 0
sign = 1
} else if s[i] == ')' {
result += sign * num
num = 0
result *= stack[len(stack)-1]
result += stack[len(stack)-2]
stack = stack[:len(stack)-2]
}
}
return result + sign*num
}
func isDigit(ch byte) bool {
return ch >= '0' && ch <= '9'
}
1
write your code here
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用