Basic Calculator III Problem
Description
LeetCode Problem 772.
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, '+', '-', '*', '/' operators, and open '(' and closing parentheses ')'. The integer division should truncate toward zero.
You may assume that the given expression is always valid. All intermediate results will be in the range of [-2^31, 2^31 - 1].
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 = "6-4/2"
Output: 4
Example 3:
Input: s = "2*(5+5*2)/3+(6/2+8)"
Output: 21
Constraints:
1 <= s <= 10^4sconsists of digits,'+','-','*','/','(', and')'.sis a valid expression.
Solution
Approach: Stack of Terms + Recursion for Parentheses
Without parentheses, an expression is a sum of terms, and each term is a product or quotient of numbers. That gives a simple one-pass method with a stack of terms:
- keep the number being read in
numand the operator that came before it inop(initially+); - when the number ends (at the next operator, a
)or the end of the string), applyop:+pushesnum,-pushes-num,*multiplies the top of the stack bynum, and/divides the top bynum; - the value of the expression is the sum of the stack.
Multiplication and division act on the stack top right away, so they bind tighter than + and -, and same-level operators are applied left to right (14/3*2 is 8).
Parentheses fit in with recursion: a ( starts a sub-expression, so call the same function, which reads up to the matching ) and returns its value. That value is used as num, exactly as if it were a number in the string. A shared index i keeps track of where the reading continues after the ).
The tricky part is division: it must truncate toward zero, so (0-7)/2 is -3, not -4. Java, C++, Go and JavaScript's Math.trunc do that; in Python, // rounds down, so use int(a / b) instead. Also note that a - is pushed as a negative term, so 1-2-3 becomes 1 + (-2) + (-3) = -4, as it should.
Complexity: O(n) time, since each character is read once. O(n) extra space for the stacks and the recursion (one level per open parenthesis).
class Solution:
def calculate(self, s: str) -> int:
i = 0 # next character to read
def evaluate() -> int:
"""Evaluate from s[i] up to the matching ')' (or the end of s) and consume it."""
nonlocal i
stack = [] # terms to add up; * and / are applied to the top right away
num, op = 0, "+" # op is the operator in front of num
while i < len(s):
c = s[i]
i += 1
if c.isdigit():
num = num * 10 + int(c)
elif c == "(":
num = evaluate()
if c in "+-*/)" or i == len(s):
if op == "+":
stack.append(num)
elif op == "-":
stack.append(-num)
elif op == "*":
stack[-1] *= num
else:
stack[-1] = int(stack[-1] / num) # truncate toward zero
if c == ")":
break
num, op = 0, c
return sum(stack)
return evaluate()