Check if the bracket sequence can be balanced with at most one change in the position of a bracket | Java implementation of the approach ; Function that returns true if the sequence can be balanced by changing the position of at most one bracket ; Odd length string can never be balanced ; Add ' ( ' in the beginning and ' ) ' in the end of the string ; If its an opening bracket then append it to the temp string ; If its a closing bracket ; There was an opening bracket to match it with ; No opening bracket to match it with ; Sequence is balanced ; Driver Code
import java . util . Vector ; class GFG { static boolean canBeBalanced ( String s , int n ) { if ( n % 2 == 1 ) return false ; String k = " ( " ; k += s + " ) " ; Vector < String > d = new Vector < > ( ) ; for ( int i = 0 ; i < k . length ( ) ; i ++ ) { if ( k . charAt ( i ) == ' ( ' ) d . add ( " ( " ) ; else { if ( d . size ( ) != 0 ) d . remove ( d . size ( ) - 1 ) ; else return false ; } } if ( d . isEmpty ( ) ) return true ; return false ; } public static void main ( String [ ] args ) { String s = " ) ( ( ) " ; int n = s . length ( ) ; if ( canBeBalanced ( s , n ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }