You are given a string composed with the characters 0123456789+*()
. You can assume that string is always a valid mathematical expression.
Your task is to remove the unnecessary parentheses, assuming multiplication has higher priority than addition.
The parentheses should be removed only when they are not needed structurally:
- because of multiplication higher priority:
3+(4*5)
=>3+4*5
- because of multiplication or addition associativity:
3*(4*5)
=>3*4*5
- when they are redundant around an expression:
3*((4+5))
=>3*(4+5)
Parentheses should be kept when they could be simplified because of specific number values:
1*(2+3)
should not be simplified to1*2+3
0*(1+0)
should not be simplified to0*1+0
Examples:
(4*12)+11 ==> 4*12+11
(1+2)*3 ==> (1+2)*3
3*(4*5) ==> 3*4*5
((((523)))) ==> 523
(1+1) ==> 1+1
1*(2*(3+4)*5)*6 ==> 1*2*(3+4)*5*6
1*(2+3) ==> 1*(2+3)
0*(1+0) ==> 0*(1+0)
(((2+92+82)*46*70*(24*62)+(94+25))+6) ==> (2+92+82)*46*70*24*62+94+25+6
1*(2*(3+4)*5)*6
should be an interesting testcase (which my solution currently fails for). \$\endgroup\$(2+2)*1
\$\endgroup\$