Remove brackets from an algebraic string containing + and | C # program to simplify algebraic string ; Function to simplify the string ; resultant string of max length equal to length of input string ; create empty stack ; If top is 1 , flip the operator ; If top is 0 , append the same operator ; x is opposite to the top of stack ; push value equal to top of the stack ; If closing parentheses pop the stack once ; copy the character to the result ; Driver code
using System ; using System . Collections . Generic ; class GfG { static String simplify ( String str ) { int len = str . Length ; char [ ] res = new char [ len ] ; int index = 0 , i = 0 ; Stack < int > s = new Stack < int > ( ) ; s . Push ( 0 ) ; while ( i < len ) { if ( str [ i ] == ' + ' ) { if ( s . Peek ( ) == 1 ) res [ index ++ ] = ' - ' ; if ( s . Peek ( ) == 0 ) res [ index ++ ] = ' + ' ; } else if ( str [ i ] == ' - ' ) { if ( s . Peek ( ) == 1 ) res [ index ++ ] = ' + ' ; else if ( s . Peek ( ) == 0 ) res [ index ++ ] = ' - ' ; } else if ( str [ i ] == ' ( ' && i > 0 ) { if ( str [ i - 1 ] == ' - ' ) { int x = ( s . Peek ( ) == 1 ) ? 0 : 1 ; s . Push ( x ) ; } else if ( str [ i - 1 ] == ' + ' ) s . Push ( s . Peek ( ) ) ; } else if ( str [ i ] == ' ) ' ) s . Pop ( ) ; else res [ index ++ ] = str [ i ] ; i ++ ; } return new String ( res ) ; } public static void Main ( String [ ] args ) { String s1 = " a - ( b + c ) " ; String s2 = " a - ( b - c - ( d + e ) ) - f " ; Console . WriteLine ( simplify ( s1 ) ) ; Console . WriteLine ( simplify ( s2 ) ) ; } }