Maximum length of balanced string after swapping and removal of characters | Java implementation of the approach ; Function to return the length of the longest balanced sub - string ; To store the count of parentheses ; Traversing the string ; Check type of parentheses and incrementing count for it ; Sum all pair of balanced parentheses ; Driven code
class GFG { static int maxBalancedStr ( String s ) { int open1 = 0 , close1 = 0 ; int open2 = 0 , close2 = 0 ; int open3 = 0 , close3 = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { switch ( s . charAt ( i ) ) { case ' ( ' : open1 ++ ; break ; case ' ) ' : close1 ++ ; break ; case ' { ' : open2 ++ ; break ; case ' } ' : close2 ++ ; break ; case ' [ ' : open3 ++ ; break ; case ' ] ' : close3 ++ ; break ; } } int maxLen = 2 * Math . min ( open1 , close1 ) + 2 * Math . min ( open2 , close2 ) + 2 * Math . min ( open3 , close3 ) ; return maxLen ; } public static void main ( String [ ] args ) { String s = " ) ) [ ] ] ( ( " ; System . out . println ( maxBalancedStr ( s ) ) ; } }