Simplify a Nested Variable Expression
Problem statement
Given a valid arithmetic expression containing lowercase one-letter variables, +, -, parentheses, and optional spaces, combine like variables and return an equivalent simplified expression.
A term is a variable or a parenthesized expression. An expression may begin with a unary + or -, and its remaining terms are joined by binary + or -. Spaces may occur between tokens. There are no numbers in the input.
In the output, list nonzero negative-coefficient variables first in alphabetical order, then nonzero positive-coefficient variables in alphabetical order. Use - before a negative term and + before a positive term, with one space on each side of every binary sign. Omit the coefficient when its absolute value is one; otherwise write the magnitude as m*variable. Return 0 if all terms cancel.
Function
simplifyExpression(expression: String) → StringExamples
Example 1
expression = "a - (b + a - (c + a))"return = "-b + a + c"The outer minus reverses the signs inside the parentheses. The two cancelling a terms leave one positive a.
Example 2
expression = "a + b - a"return = "b"The positive and negative a terms cancel.
Example 3
expression = "-(x - (y + x))"return = "y"Negating the outer group leaves -x + y + x, so only y remains.
Example 4
expression = "a - a"return = "0"All variable coefficients become zero.
Constraints
1 <= expression.length <= 100000.- The input is a valid expression of one-letter variables, unary or binary signs, parentheses and spaces as described above.
- Every variable is a lowercase English letter.