Balance a string after removing extra brackets | Print balanced and remove extra brackets from string ; Maintain a count for opening brackets Traversing string ; check if opening bracket ; print str [ i ] and increment count by 1 ; check if closing bracket and count != 0 ; decrement count by 1 ; if str [ i ] not a closing brackets print it ; balanced brackets if opening brackets are more then closing brackets ; print remaining closing brackets ; Driver code
< ? php function balancedString ( $ str ) { $ count = 0 ; $ n = strlen ( $ str ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ str [ $ i ] == ' ( ' ) { echo $ str [ $ i ] ; $ count ++ ; } else if ( $ str [ $ i ] == ' ) ' && $ count != 0 ) { echo $ str [ $ i ] ; $ count -- ; } else if ( $ str [ $ i ] != ' ) ' ) echo $ str [ $ i ] ; } if ( $ count != 0 ) for ( $ i = 0 ; $ i < $ count ; $ i ++ ) echo " ) " ; } $ str = " gau ) ra ) v ( ku ( mar ( rajput ) ) " ; balancedString ( $ str ) ; ? >