Maximum length of balanced string after swapping and removal of characters | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; 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 [ i ] ) { case ' ( ' : open1 ++ ; break ; case ' ) ' : close1 ++ ; break ; case ' { ' : open2 ++ ; break ; case ' } ' : close2 ++ ; break ; case ' [ ' : open3 ++ ; break ; case ' ] ' : close3 ++ ; break ; } } int maxLen = 2 * min ( open1 , close1 ) + 2 * min ( open2 , close2 ) + 2 * min ( open3 , close3 ) ; return maxLen ; } int main ( ) { string s = " ) ) [ ] ] ( ( " ; cout << maxBalancedStr ( s ) ; return 0 ; }