Remove Redundant Parentheses
InterviewTime limit1sMemory limit128 MB
Given valid arithmetic expressions over single uppercase variables with + and -, remove every matching parenthesis pair whose removal keeps the expression's value unchanged.
- Level
Medium6 of 10
- Topics
- Stack, String, Implementation, Greedy
- Solved
- No attempts yet
Problem
You typed the report for your term project on your personal computer. The report contains several one-line arithmetic expressions. The original expressions have no redundant parentheses. A pair of matching parentheses is redundant if removing that single pair does not change the value of the expression.
While you were away, your younger sibling inserted some redundant pairs of matching parentheses into the expressions. Assume that afterwards each expression is still syntactically correct and still evaluates to its original value (the value before the parentheses were inserted).
Write a program that removes all redundant parentheses to restore each expression to its original form.
To keep things simple, assume the following:
- The input contains several expressions, one per line.
- Every variable in the expressions is a single uppercase letter.
- The only operators are the binary '+' and the binary '-'.
The only transformation allowed is the omission of redundant parentheses; no algebraic simplification is allowed.
Input
The first line contains a single integer , the number of test cases (). Each of the next lines contains exactly one valid expression. A line may contain arbitrary space characters, and the length of each line (including spaces) is at most characters.
Output
For each test case, print the expression with all redundant parentheses removed, one per line. The order of the operands must be the same in the input and in the output. Remove every space character from the output expressions.