Find the lexicographical next balanced bracket sequence | Java implementation of the approach ; makes a string containing char d c number of times ; 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
class Sol { static String string ( int c , char d ) { String s = " " ; for ( int i = 0 ; i < c ; i ++ ) s += d ; return s ; } static String next_balanced_sequence ( String s ) { String next = " - 1" ; int length = s . length ( ) ; int depth = 0 ; for ( int i = length - 1 ; i >= 0 ; -- i ) { if ( s . charAt ( i ) == ' ( ' ) depth -- ; else depth ++ ; if ( s . charAt ( i ) == ' ( ' && depth > 0 ) { depth -- ; int open = ( length - i - 1 - depth ) / 2 ; int close = length - i - 1 - open ; next = s . substring ( 0 , i ) + ' ) ' + string ( open , ' ( ' ) + string ( close , ' ) ' ) ; break ; } } return next ; } public static void main ( String args [ ] ) { String s = " ( ( ( ) ) ) " ; System . out . println ( next_balanced_sequence ( s ) ) ; } }