32
6
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
1More testcases please? – Leaky Nun – 2016-05-05T10:20:16.377
Not a trivial task. Somewhat related: http://codegolf.stackexchange.com/questions/67651/parenthesize-an-expression/68089
– edc65 – 2016-05-05T10:32:05.1502
1*(2*(3+4)*5)*6
should be an interesting testcase (which my solution currently fails for). – Leaky Nun – 2016-05-05T10:46:38.8271There won't be whitespace in the expression, right? – orlp – 2016-05-05T11:12:53.017
@orlp no whitespace, only
0123456789+*()
– Arnaud – 2016-05-05T11:20:35.5908Is "unnecessary" defined structurally or on a per-case basis? In other words, are the parentheses unnecessary here?
(2+2)*1
– Luis Mendo – 2016-05-05T14:00:47.3702@LuisMendo I think it's fair to interpret it in either way – anatolyg – 2016-05-05T16:49:47.717
2@anatolyg I don't think that'd be fair, because the approaches for the two would be very different. It would be good if we got some clarification. – Sp3000 – 2016-05-06T23:23:31.787
1@Sp3000 I've added more details. I should have used variables
[a..z]
rather than numbers... – Arnaud – 2016-05-07T04:52:14.590