Count pairs of parentheses sequences such that parentheses are balanced | Java 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
import java . util . HashMap ; class GFG { static int countPairs ( String [ ] bracks , int num ) { HashMap < Integer , Integer > open = new HashMap < > ( ) ; HashMap < Integer , Integer > close = new HashMap < > ( ) ; 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 . charAt ( j ) == ' ( ' ) op ++ ; else { if ( op != 0 ) op -- ; else cl ++ ; } } if ( op != 0 && cl == 0 ) open . put ( op , open . get ( op ) == null ? 1 : open . get ( op ) + 1 ) ; if ( cl != 0 && op == 0 ) close . put ( cl , close . get ( cl ) == null ? 1 : close . get ( cl ) + 1 ) ; if ( op == 0 && cl == 0 ) cnt ++ ; } cnt /= 2 ; for ( HashMap . Entry < Integer , Integer > it : open . entrySet ( ) ) cnt += Math . min ( it . getValue ( ) , close . get ( it . getKey ( ) ) ) ; return cnt ; } public static void main ( String [ ] args ) { String [ ] bracks = { " ) ( ) ) " , " ) " , " ( ( " , " ( ( " , " ( " , " ) " , " ) " } ; int num = bracks . length ; System . out . println ( countPairs ( bracks , num ) ) ; } }