Check if a given string can be converted to a Balanced Bracket Sequence | C # program for the above approach ; Function to check if the String can be balanced by replacing the ' $ ' with opening or closing brackets ; If String can never be balanced ; Declare 2 stacks to check if all ) can be balanced with ( or $ and vice - versa ; Store the count the occurence of ( , ) and $ ; Traverse the String ; Increment closed bracket count by 1 ; If there are no opening bracket to match it then return false ; Otherwise , pop the character from the stack ; If current character is an opening bracket or $ , push it to the stack ; Increment symbol count by 1 ; Increment open bracket count by 1 ; Traverse the String from end and repeat the same process ; If there are no closing brackets to match it ; Otherwise , pop character from stack ; Store the extra ( or ) which are not balanced yet ; Check if $ is available to balance the extra brackets ; Count ramaining $ after balancing extra ( and ) ; Check if each pair of $ is convertable in ( ) ; Driver Code ; Function Call
using System ; using System . Collections . Generic ; class GFG { static bool canBeBalanced ( String sequence ) { if ( sequence . Length % 2 == 1 ) return false ; Stack < char > stack_ = new Stack < char > ( ) ; Stack < char > stack2_ = new Stack < char > ( ) ; int countOpen = 0 , countClosed = 0 ; int countSymbol = 0 ; for ( int i = 0 ; i < sequence . Length ; i ++ ) { if ( sequence [ i ] == ' ) ' ) { countClosed ++ ; if ( stack_ . Count == 0 ) { return false ; } else { stack_ . Pop ( ) ; } } else { if ( sequence [ i ] == ' $ ' ) { countSymbol ++ ; } else { countOpen ++ ; } stack_ . Push ( sequence [ i ] ) ; } } for ( int i = sequence . Length - 1 ; i >= 0 ; i -- ) { if ( sequence [ i ] == ' ( ' ) { if ( stack2_ . Count == 0 ) { return false ; } else { stack2_ . Pop ( ) ; } } else { stack2_ . Push ( sequence [ i ] ) ; } } int extra = Math . Abs ( countClosed - countOpen ) ; if ( countSymbol < extra ) { return false ; } else { countSymbol -= extra ; if ( countSymbol % 2 == 0 ) { return true ; } } return false ; } public static void Main ( String [ ] args ) { String S = " ( ) ( $ " ; if ( canBeBalanced ( S ) ) { Console . Write ( " Yes " ) ; } else { Console . Write ( " No " ) ; } } }