Modify a numeric string to a balanced parentheses by replacements | C ++ program for the above approach ; Function to check if the given string can be converted to a balanced bracket sequence or not ; Check if the first and last characters are equal ; Initialize two variables to store the count of open and closed brackets ; If the current character is same as the first character ; If the current character is same as the last character ; If count of open brackets becomes less than 0 ; Print the new string ; If the current character is same as the first character ; If bracket sequence is not balanced ; Check for unbalanced bracket sequence ; Print the sequence ; Driver Code ; Given Input ; Function Call
#include <iostream> NEW_LINE using namespace std ; void balBracketSequence ( string str ) { int n = str . size ( ) ; if ( str [ 0 ] == str [ n - 1 ] ) { cout << " No " << endl ; } else { int cntForOpen = 0 , cntForClose = 0 ; int check = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == str [ 0 ] ) cntForOpen ++ ; else if ( str [ i ] == str [ n - 1 ] ) cntForOpen -- ; else cntForOpen ++ ; if ( cntForOpen < 0 ) { check = 0 ; break ; } } if ( check && cntForOpen == 0 ) { cout << " Yes , ▁ " ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == str [ n - 1 ] ) cout << ' ) ' ; else cout << ' ( ' ; } return ; } else { for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == str [ 0 ] ) cntForClose ++ ; else cntForClose -- ; if ( cntForClose < 0 ) { check = 0 ; break ; } } if ( check && cntForClose == 0 ) { cout << " Yes , ▁ " ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == str [ 0 ] ) cout << ' ( ' ; else cout << ' ) ' ; } return ; } } cout << " No " ; } } int main ( ) { string str = "123122" ; balBracketSequence ( str ) ; return 0 ; }