224. Basic Calculator
时不时写点设计题
题干:
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .
解释:
给一个字符串表达式,要求计算他的返回值
思考:
首先,使用3个标志位,sign代表接下来的表达式是正还是负,每次运算结束之后置为1,res代表当前表达式的值,num代表当前数字的值,每次运算之后要清零。遇到括号就初始化,并且把表达式的正负保存下来,压入栈中。遇到右括号再取出来即可。 代码非常清晰简介。89.6
答案:
from collections import deque
class Solution(object):
def calculate(self, s:str):
"""
:type s: str
:rtype: int
"""
res = 0
sign = 1
num = 0
stack =[]
for c in s:
if c.isdigit():
#解决了连续数字的问题
num = num*10+int(c)
elif c == '+' or c == '-':
res = res+num*sign
sign =1 if c =='+' else -1
num = 0
elif c =='(':
stack.append(res)
stack.append(sign)
sign =1
res =0
elif c ==')':
res = res + sign*num
old_sign = stack.pop()
old_res = stack.pop()
res =old_res+old_sign*res
sign =1
num =0
res = res+sign*num
return res