Count of substrings having the most frequent character in the string as first character | Java 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
import java . util . * ; class GFG { static int substringCount ( String s ) { int [ ] freq = new int [ 26 ] ; char max_char = ' # ' ; int maxfreq = Integer . MIN_VALUE ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { freq [ s . charAt ( i ) - ' a ' ] ++ ; if ( maxfreq < freq [ s . charAt ( i ) - ' a ' ] ) maxfreq = freq [ s . charAt ( 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 . length ( ) ; i ++ ) { char ch = s . charAt ( i ) ; if ( max_char == ch ) { ans += ( s . length ( ) - i ) ; } } return ans ; } public static void main ( String [ ] args ) { String S = " abcab " ; System . out . println ( substringCount ( S ) ) ; } }