Modify a numeric string to a balanced parentheses by replacements | Java 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
import java . util . * ; class GFG { static void balBracketSequence ( String str ) { int n = str . length ( ) ; if ( str . charAt ( 0 ) == str . charAt ( n - 1 ) ) { System . out . println ( " No " ) ; } else { int cntForOpen = 0 , cntForClose = 0 ; int check = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) == str . charAt ( 0 ) ) cntForOpen ++ ; else if ( str . charAt ( i ) == str . charAt ( n - 1 ) ) cntForOpen -= 1 ; else cntForOpen += 1 ; if ( cntForOpen < 0 ) { check = 0 ; break ; } } if ( check != 0 && cntForOpen == 0 ) { System . out . print ( " Yes , ▁ " ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) == str . charAt ( n - 1 ) ) System . out . print ( ' ) ' ) ; else System . out . print ( ' ( ' ) ; } return ; } else { for ( int i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) == str . charAt ( 0 ) ) cntForClose ++ ; else cntForClose -- ; if ( cntForClose < 0 ) { check = 0 ; break ; } } if ( check != 0 && cntForClose == 0 ) { System . out . print ( " Yes , ▁ " ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) == str . charAt ( 0 ) ) System . out . print ( ' ( ' ) ; else System . out . print ( ' ) ' ) ; } return ; } } System . out . print ( " No " ) ; } } public static void main ( String args [ ] ) { String str = "123122" ; balBracketSequence ( str ) ; } }