Check if the bracket sequence can be balanced with at most one change in the position of a bracket | C # 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
using System ; using System . Collections . Generic ; class GFG { static bool canBeBalanced ( string s , int n ) { if ( n % 2 == 1 ) return false ; string k = " ( " ; k += s + " ) " ; List < string > d = new List < string > ( ) ; for ( int i = 0 ; i < k . Length ; i ++ ) { if ( k [ i ] == ' ( ' ) d . Add ( " ( " ) ; else { if ( d . Count != 0 ) d . RemoveAt ( d . Count - 1 ) ; else return false ; } } if ( d . Count == 0 ) return true ; return false ; } public static void Main ( ) { string s = " ) ( ( ) " ; int n = s . Length ; if ( canBeBalanced ( s , n ) ) Console . Write ( " Yes " ) ; else Console . Write ( " No " ) ; } }