Parenthesized String Calculator
Problem statement
Evaluate a valid arithmetic expression containing nonnegative decimal integers, binary + and -, parentheses, and optional spaces.
Return the integer result. Every operator has an operand on both sides, parentheses are balanced, and all intermediate values fit signed 32-bit range.
Function
calculate(expression: String) → intExamples
Example 1
expression = "1 + (2 - 3) + 10"return = 10The parenthesized term equals -1.
Example 2
expression = "12-(4+(2-1))"return = 7The inner expression is 1, so the grouped value is 5.
Example 3
expression = "42"return = 42A single literal evaluates to itself.
Constraints
1 <= expression.length <= 10^5.- The expression grammar is valid and uses only digits, spaces,
+,-,(, and). - Operators are binary; unary signs are not present.