Basic Calculator Problem
Description
LeetCode Problem 224.
Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
Example 1:
Input: s = "1 + 1"
Output: 2
Example 2:
Input: s = " 2-1 + 2 "
Output: 3
Example 3:
Input: s = "(1+(4+5+2)-3)+(6+8)"
Output: 23
Constraints:
- 1 <= s.length <= 3 * 10^5
- s consists of digits, '+', '-', '(', ')', and ' '.
- s represents a valid expression.
- '+' is not used as a unary operation (i.e., "+1" and "+(2 + 3)" is invalid).
- '-' could be used as a unary operation (i.e., "-1" and "-(2 + 3)" is valid).
- There will be no two consecutive operators in the input.
- Every number and running calculation will fit in a signed 32-bit integer.
Solution
Approach: Running Sum with a Stack of Signs
With only + and -, the value of an expression is a sum of signed numbers. Read the string from left to right and keep a running result. For every number, add sign * number, where sign is +1 or -1 depending on the operator before it.
Parentheses only change which sign applies inside them. When we reach (, the part inside is a new expression, so we save the current result and the sign in front of the ( on a stack, then start again with result = 0 and sign = 1. When we reach ), the inner value is complete, and we combine it with the saved state: result = outerResult + signBefore * result.
Steps for each character:
- digit: extend the current number,
number = number * 10 + digit. Numbers can have several digits. +or-: the number before it is complete. Addsign * numbertoresult, resetnumber, and setsignfrom this operator.(: pushresultandsign, then reset both.): add the last number, then pop and combine as above.- space: skip it.
At the end, add the last pending number: result + sign * number.
A unary minus, as in "-(2 + 3)" or "1-(-2)", needs no special case. It appears where result and number are both 0, so adding 0 and setting sign = -1 is all that is needed.
Complexity: O(n) time and O(n) space for the stack in the worst case (deeply nested parentheses), where n is the length of s.
class Solution:
def calculate(self, s: str) -> int:
result = 0 # value of the current parenthesis level so far
sign = 1 # sign in front of the number being read
number = 0 # digits read so far
stack = [] # for each open "(": the outer result and the sign before "("
for ch in s:
if ch.isdigit():
number = number * 10 + int(ch)
elif ch == "+" or ch == "-":
result += sign * number
number = 0
sign = 1 if ch == "+" else -1
elif ch == "(":
# Save the outer level and start a fresh one inside the parentheses.
stack.append(result)
stack.append(sign)
result = 0
sign = 1
elif ch == ")":
result += sign * number
number = 0
sign_before = stack.pop()
outer_result = stack.pop()
result = outer_result + sign_before * result
# spaces are skipped
return result + sign * number