Count pairs of parentheses sequences such that parentheses are balanced | C # program to count the number of pairs of balanced parentheses ; Function to count the number of pairs ; Hashing function to count the opening and closing brackets ; Traverse for all bracket sequences ; Get the string ; Counts the opening and closing required ; Traverse in the string ; If it is a opening bracket ; Closing bracket ; If openings are there , then close it ; Else increase count of closing ; If requirements of openings are there and no closing ; If requirements of closing are there and no opening ; Perfect ; Divide by two since two perfect makes one pair ; Traverse in the open and find corresponding minimum ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static int countPairs ( string [ ] bracks , int num ) { Dictionary < int , int > open = new Dictionary < int , int > ( ) ; Dictionary < int , int > close = new Dictionary < int , int > ( ) ; int cnt = 0 ; for ( int i = 0 ; i < num ; i ++ ) { string s = bracks [ i ] ; int l = s . Length ; int op = 0 , cl = 0 ; for ( int j = 0 ; j < l ; j ++ ) { if ( s [ j ] == ' ( ' ) op ++ ; else { if ( op != 0 ) op -- ; else cl ++ ; } } if ( op != 0 && cl == 0 ) { if ( open . ContainsKey ( op ) ) { open [ op ] ++ ; } else { open [ op ] = 1 ; } } if ( cl != 0 && op == 0 ) { if ( close . ContainsKey ( cl ) ) { close [ cl ] ++ ; } else { close [ cl ] = 1 ; } } if ( op == 0 && cl == 0 ) cnt ++ ; } cnt /= 2 ; foreach ( KeyValuePair < int , int > it in open ) { cnt += Math . Min ( it . Value , close [ it . Value ] ) ; } return cnt ; } public static void Main ( string [ ] args ) { string [ ] bracks = { " ) ( ) ) " , " ) " , " ( ( " , " ( ( " , " ( " , " ) " , " ) " } ; int num = bracks . Length ; Console . Write ( countPairs ( bracks , num ) ) ; } }