Basic Calculator LeetCode solution in Python
1# Runtime: 137 ms (Top 57.95%) | Memory: 15.5 MB (Top 50.78%)234class Solution:5def calculate(self, s: str) -> int:6curr, output, sign, stack = 0, 0, 1, []78for ch in s:9if ch.isdigit():10curr = curr * 10 + int(ch)1112elif ch == "+":13output += sign * curr14sign = 115curr = 01617elif ch == "-":18output += sign * curr19sign = -120curr = 02122elif ch == "(":23# push the result and then the sign24stack.append(output)25stack.append(sign)26sign = 127output = 02829elif ch == ")":30output += sign * curr31output *= stack.pop()32output += stack.pop()33curr = 034return output + sign * curr