Count of substrings having the most frequent character in the string as first character | C ++ program for the above approach ; Function to find all substrings whose first character occurs maximum number of times ; Stores frequency of characters ; Stores character that appears maximum number of times ; Stores max frequency of character ; Updates frequency of characters ; Update maxfreq ; Character that occures maximum number of times ; Update the maximum frequency character ; Stores all count of substrings ; Traverse over string ; Get the current character ; Update count of substrings ; Return the count of all valid substrings ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int substringCount ( string s ) { vector < int > freq ( 26 , 0 ) ; char max_char = ' # ' ; int maxfreq = INT_MIN ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { freq [ s [ i ] - ' a ' ] ++ ; if ( maxfreq < freq [ s [ i ] - ' a ' ] ) maxfreq = freq [ s [ i ] - ' a ' ] ; } for ( int i = 0 ; i < 26 ; i ++ ) { if ( maxfreq == freq [ i ] ) { max_char = ( char ) ( i + ' a ' ) ; break ; } } int ans = 0 ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { char ch = s [ i ] ; if ( max_char == ch ) { ans += ( s . size ( ) - i ) ; } } return ans ; } int main ( ) { string S = " abcab " ; cout << ( substringCount ( S ) ) ; }