Find the lexicographical next balanced bracket sequence | C ++ implementation of the approach ; Function to find the lexicographically next balanced bracket expression if possible ; Decrement the depth for every opening bracket ; Increment for the closing brackets ; Last opening bracket ; Generate the required string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string next_balanced_sequence ( string & s ) { string next = " - 1" ; int length = s . size ( ) ; int depth = 0 ; for ( int i = length - 1 ; i >= 0 ; -- i ) { if ( s [ i ] == ' ( ' ) depth -- ; else depth ++ ; if ( s [ i ] == ' ( ' && depth > 0 ) { depth -- ; int open = ( length - i - 1 - depth ) / 2 ; int close = length - i - 1 - open ; next = s . substr ( 0 , i ) + ' ) ' + string ( open , ' ( ' ) + string ( close , ' ) ' ) ; break ; } } return next ; } int main ( ) { string s = " ( ( ( ) ) ) " ; cout << next_balanced_sequence ( s ) ; return 0 ; }