Count of sub | Function to return the count of valid sub - Strings ; Variable ans to store all the possible subStrings Initialize its value as total number of subStrings that can be formed from the given String ; Stores recent index of the characters ; If character is a update a 's index  and the variable ans ; If character is b update b 's index  and the variable ans ; If character is c update c 's index  and the variable ans ; Driver code
def CountSubString ( Str , n ) : NEW_LINE INDENT ans = ( n * ( n + 1 ) ) // 2 NEW_LINE a_index = 0 NEW_LINE b_index = 0 NEW_LINE c_index = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( Str [ i ] == ' a ' ) : NEW_LINE INDENT a_index = i + 1 NEW_LINE ans -= min ( b_index , c_index ) NEW_LINE DEDENT elif ( Str [ i ] == ' b ' ) : NEW_LINE INDENT b_index = i + 1 NEW_LINE ans -= min ( a_index , c_index ) NEW_LINE DEDENT else : NEW_LINE INDENT c_index = i + 1 NEW_LINE ans -= min ( a_index , b_index ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT Str = " babac " NEW_LINE n = len ( Str ) NEW_LINE print ( CountSubString ( Str , n ) ) NEW_LINE