text: Longest Substring having equal count of Vowels and Consonants | C ++ Program to implement the above approach ; Function to return the length of the longest substring having equal number of vowel and consonant ; Generate the array ; Initialize variable to store result ; Stores the sum of subarray ; Map to store indices of the sum ; Loop through the array ; If sum is 0 ; Count of vowels and consonants are equal ; Update the maximum length of substring in HashMap ; Store the index of the sum ; Return the maximum length of required substring ; Driver Code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxsubstringLength ( string S , int N ) { int arr [ N ] ; for ( int i = 0 ; i < N ; i ++ ) if ( S [ i ] == ' a ' S [ i ] == ' e ' S [ i ] == ' i ' S [ i ] == ' o ' S [ i ] == ' u ' ) arr [ i ] = 1 ; else arr [ i ] = -1 ; int maxLen = 0 ; int curr_sum = 0 ; unordered_map < int , int > hash ; for ( int i = 0 ; i < N ; i ++ ) { curr_sum += arr [ i ] ; if ( curr_sum == 0 ) maxLen = max ( maxLen , i + 1 ) ; if ( hash . find ( curr_sum ) != hash . end ( ) ) maxLen = max ( maxLen , i - hash [ curr_sum ] ) ; else hash [ curr_sum ] = i ; } return maxLen ; } int main ( ) { string S = " geeksforgeeks " ; int n = sizeof ( S ) / sizeof ( S [ 0 ] ) ; cout << maxsubstringLength ( S , n ) ; return 0 ; }