Evaluate a Calculator Expression With Parentheses

Implement calculate

Implement a calculator that evaluates a string expression s containing non-negative integers, +, -, and matched parentheses — no multiplication, division, or spaces — respecting the fact that a sign in front of a parenthesized group applies to the whole group, not just its first term. Since there's no operator precedence to worry about here — only left-to-right evaluation and the way parentheses can flip a sign across an entire sub-expression — a single pass suffices, as long as entering and leaving a parenthesized group is handled correctly. Pushing the outer context (the result and sign pending before the group started) onto a stack the moment '(' is seen, and popping it back the moment ')' is seen, means never needing to know in advance where a group ends: the stack remembers exactly what to resume, exactly when it's needed.

Example 1:

Input: s = "12+7"

Output: 19

Example 2:

Input: s = "(5-2)+9"

Output: 12

Example 3:

Input: s = "20-(3+4)"

Output: 13

+ 5 hidden test cases run on Submit.

Constraints:

  • 1 ≤ s.length ≤ 20
  • s contains non-negative integers (possibly multi-digit), the operators '+' and '-', and matched parentheses — no spaces, no '*' or '/'
  • A leading '-' before the whole expression or right after '(' is allowed (e.g. "-5+3")
  • The result always fits in a 32-bit signed integer

s =

12+7