Question
Given a string
srepresenting 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().
Ideas:
- This is Leetcode - Basic Calculator II with the twist that the input string can include
() - Whenever we encounter parens, we enter into a BCII sub problem
- On
(- Save current state (stack, lastOp)
- Reset state for subproblem
- On
)- Push currNum to stack based on lastOp rule
- val is sum of stack
- set val to CurrNum since this is the inner expression evaluated
- Pop last state from context and revive stack, lastOp
- There is one edge case for unary
‘-’where if there is no currNum, just pretend that currNum is 0