Remove Parentheses from a Plus-Minus Expression
Problem statement
You are given a valid arithmetic expression expression. Each operand is a single lowercase letter, the only operators are binary + and -, and parentheses group terms. There is no unary minus.
Rewrite the expression without parentheses so that it still means the same thing. Keep every operand in its original order and give it the sign it ends up with once all the parentheses are opened: a group after - flips the sign of everything inside it, and a group after + (or at the start) changes nothing. Do not combine repeated letters.
Return the result as a string. The first operand is always positive and is written with no sign; every later operand is preceded by + or -.
Function
simplifyExpression(expression: String) → StringExamples
Example 1
expression = "a-(b-c)"return = "a-b+c"The group (b-c) is subtracted, so every sign inside it flips: b becomes -b and -c becomes +c.
Example 2
expression = "a-(b+(c-d))+e"return = "a-b-c+d+e"The outer group is subtracted, so b and the inner group (c-d) both flip. Inside the inner group, c was added and d subtracted; after the outer flip, c becomes -c and d becomes +d. The +e after the groups keeps its sign.
Example 3
expression = "(a+b)-(a-b)"return = "a+b-a+b"The first group is added, so a and b keep their signs. The second group is subtracted, giving -a+b. Terms are never combined, so both a terms and both b terms stay, in their original order.
Constraints
1 <= expression.length < 104expressioncontains only lowercase English letters,'+','-','('and')'.expressionis a valid expression: every letter is one operand,'+'and'-'are binary operators between two terms, and every parenthesized group is non-empty and balanced.- Parentheses are nested at most
50levels deep.