Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def calculate(self, s: str) -> int:
- stack = []
- res = 0
- num = 0
- sign = 1 # current sign (1 means '+', -1 means '-')
- for ch in s:
- if ch.isdigit():
- num = num * 10 + int(ch)
- elif ch in "+-":
- res += sign * num
- num = 0
- sign = 1 if ch == "+" else -1
- elif ch == "(":
- # push current result and sign
- stack.append(res)
- stack.append(sign)
- res = 0
- sign = 1
- elif ch == ")":
- res += sign * num
- num = 0
- res *= stack.pop() # sign before parenthesis
- res += stack.pop() # previous result
- # ignore spaces
- return res + sign * num
Advertisement
Add Comment
Please, Sign In to add comment