Remove brackets from an algebraic string containing + and | Java 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 program
import java . util . * ; class GfG { static String simplify ( String str ) { int len = str . length ( ) ; char res [ ] = new char [ len ] ; int index = 0 , i = 0 ; Stack < Integer > s = new Stack < Integer > ( ) ; s . push ( 0 ) ; while ( i < len ) { if ( str . charAt ( i ) == ' + ' ) { if ( s . peek ( ) == 1 ) res [ index ++ ] = ' - ' ; if ( s . peek ( ) == 0 ) res [ index ++ ] = ' + ' ; } else if ( str . charAt ( i ) == ' - ' ) { if ( s . peek ( ) == 1 ) res [ index ++ ] = ' + ' ; else if ( s . peek ( ) == 0 ) res [ index ++ ] = ' - ' ; } else if ( str . charAt ( i ) == ' ( ' && i > 0 ) { if ( str . charAt ( i - 1 ) == ' - ' ) { int x = ( s . peek ( ) == 1 ) ? 0 : 1 ; s . push ( x ) ; } else if ( str . charAt ( i - 1 ) == ' + ' ) s . push ( s . peek ( ) ) ; } else if ( str . charAt ( i ) == ' ) ' ) s . pop ( ) ; else res [ index ++ ] = str . charAt ( 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 " ; System . out . println ( simplify ( s1 ) ) ; System . out . println ( simplify ( s2 ) ) ; } }