Evaluate an arithmetic expression string containing non-negative integers, +, -, parentheses, and spaces.
Problem
Given a string s representing a valid arithmetic expression, compute its value.
The expression may contain:
- non-negative integers
- the operators
+and- - parentheses
(and) - spaces
You must evaluate the expression according to normal arithmetic rules for addition and subtraction, including nested parentheses.
Goal
Return the integer result of the expression.
Input Format
- A single string
srepresenting a valid arithmetic expression. - The expression may contain digits, spaces,
+,-,(, and).
Output Format
- Return a single integer: the evaluated value of the expression.
Constraints
- The expression is valid.
- Only addition and subtraction are required.
- Parentheses may be nested arbitrarily.
- Spaces may appear anywhere in the string.
- Intermediate and final results fit in 32-bit signed integer range.
Example 1
Input
s = "1 + 1"
Output
2
Explanation
1 + 1 = 2.
Example 2
Input
s = "2-(5-6)"
Output
3
Explanation
First evaluate the inner parentheses: 5 - 6 = -1. Then 2 - (-1) = 3.
Show 1 more example
Example 3
Input
s = "(1+(4+5+2)-3)+(6+8)"
Output
23
Explanation
Evaluate each parenthesized group, then combine them: 1 + 11 - 3 + 14 = 23.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.