Given an expression containing numeric operands with addition and subtraction operators, evaluate it. Assume that the expression is valid and may contain sub-expressions enclosed in opening and closing braces.

For example,

Input: s = -15-2+1
Output: -16
 
Input: s = -10+(5+(12+8)-2)+1
Output: 14

We can easily compute a mathematical expression containing only addition and subtraction operators using a stack. The idea is based on the fact that whenever a negative sign is present outside of parentheses, all numbers inside the parentheses have their sign reversed.

 
We traverse the given expression from left to right. If the current character of the expression is a digit, construct the full number; otherwise, if the current character is a plus or minus sign, add the preceding number to the result in accordance with the sign outside the parentheses (if any). Here, '+' would have no impact on the sign inside the parentheses, whereas '-' would negate the sign inside the parentheses. We push the sign to the stack if the current character is an opening brace, and pop the sign from the stack if the current character is a closing brace.

 
This approach is demonstrated below in C++, Java, and Python. Note that the sign before each set of parenthesis is stored in a stack.

C++


Download  Run Code

Output:

14

Java


Download  Run Code

Output:

14

Python


Download  Run Code

Output:

14

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the length of the expression.