Skip to content
BytePatterns

Evaluate Sums With Brackets

HardStacks & Queues#stack#expression-parsing#sign-tracking~40m

Problem

A spreadsheet cell holds a formula made of non-negative integers, +, -, round brackets and spaces. A - may also be unary, as in "-(2 + 3)" or "1 - (-2)". Return the value of the formula without calling any built-in evaluator. The formula is valid, is at most 300,000 characters long, and every intermediate value fits in a 32-bit signed integer, so the parser must run in linear time.

Examples

Input:  s = "1 + 1"
Output: 2
Input:  s = "(1+(4+5+2)-3)+(6+8)"
Output: 23
Input:  s = "-(2 + 3) - (1 - 10)"
Output: 4
Why:    a unary minus in front of a bracket flips the sign of its whole value

Hints

0 / 3

Stuck on the idea rather than the code? Valid Parentheses covers it.