Convert an unbalanced bracket sequence to a balanced sequence | C ++ implementation of the approach ; Function to return balancedBrackets string ; Initializing dep to 0 ; Stores maximum negative depth ; if dep is less than minDep ; if minDep is less than 0 then there is need to add ' ( ' at the front ; Reinitializing to check the updated string ; if dep is not 0 then there is need to add ' ) ' at the back ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string balancedBrackets ( string str ) { int dep = 0 ; int minDep = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] == ' ( ' ) dep ++ ; else dep -- ; if ( minDep > dep ) minDep = dep ; } if ( minDep < 0 ) { for ( int i = 0 ; i < abs ( minDep ) ; i ++ ) str = ' ( ' + str ; } dep = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] == ' ( ' ) dep ++ ; else dep -- ; } if ( dep != 0 ) { for ( int i = 0 ; i < dep ; i ++ ) str = str + ' ) ' ; } return str ; } int main ( ) { string str = " ) ) ) ( ) " ; cout << balancedBrackets ( str ) ; }