Balance a string after removing extra brackets | C ++ implementation of above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void balancedString ( string str ) { int count = 0 , i ; int n = str . length ( ) ; for ( i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ' ( ' ) { cout << str [ i ] ; count ++ ; } else if ( str [ i ] == ' ) ' && count != 0 ) { cout << str [ i ] ; count -- ; } else if ( str [ i ] != ' ) ' ) cout << str [ i ] ; } if ( count != 0 ) for ( i = 0 ; i < count ; i ++ ) cout << " ) " ; } int main ( ) { string str = " gau ) ra ) v ( ku ( mar ( rajput ) ) " ; balancedString ( str ) ; return 0 ; }