Ideas
对于表达式计算的问题,一般第一个想到的就是stack,每次从表达式中拿一个值放到stack中,如果是乘除,因为优先级比较高,所以先计算,然后把计算结果append到stack中。
Code
Python
import operator
class Solution:
def calculate(self, s: str) -> int:
stack = []
op = {
'+': lambda x: stack.append(x),
'-': lambda x: stack.append(-x),
'*': lambda x: stack.append(x * stack.pop()),
'/': lambda x: stack.append(int(operator.truediv(stack.pop(), x))),
}
pre, num = '+', 0
for c in s + '+':
if c.isdigit():
num = num * 10 + ord(c) - ord('0')
elif c != ' ':
op[pre](num)
pre = c
num = 0
return sum(stack)