You're building a smart calculator that can evaluate mathematical expressions from strings! Given a string s representing a valid mathematical expression, your task is to implement a basic calculator that can handle:
- Addition (
+) and subtraction (-) - Parentheses for grouping operations
- Spaces that should be ignored
For example, "1 + 1" should return 2, and "(1+(4+5+2)-3)+(6+8)" should return 23.
Important: You cannot use built-in functions like eval() - you need to parse and evaluate the expression yourself!
This is a classic problem that tests your understanding of expression parsing, operator precedence, and data structures like stacks.
Input & Output
Visualization
Time & Space Complexity
For each level of parentheses (O(n)), we scan the entire string (O(n)) and create new strings (O(n))
Recursive calls and string creation at each level
Constraints
- 1 โค s.length โค 3 ร 105
- s consists of digits, '+', '-', '(', ')', and ' '
- s represents a valid expression
- '+' is not used as a unary operation
- '-' 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