Count of substrings having the most frequent character in the string as first character | Python3 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 max_char = ; 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 sys NEW_LINE def substringCount ( s ) : NEW_LINE INDENT freq = [ 0 for i in range ( 26 ) ] NEW_LINE DEDENT INDENT maxfreq = - sys . maxsize - 1 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE if ( maxfreq < freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] ) : NEW_LINE INDENT maxfreq = freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] NEW_LINE DEDENT DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( maxfreq == freq [ i ] ) : NEW_LINE INDENT max_char = chr ( i + ord ( ' a ' ) ) NEW_LINE break NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT ch = s [ i ] NEW_LINE if ( max_char == ch ) : NEW_LINE INDENT ans += ( len ( s ) - i ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " abcab " NEW_LINE print ( substringCount ( S ) ) NEW_LINE DEDENT