Count of substrings formed using a given set of characters only | Function to find the number of substrings that can be formed using given characters ; Boolean array for storing the available characters ; Mark indices of all available characters as 1 ; Initialize lastPos as - 1 ; Initialize ans with the total no of possible substrings ; Traverse the string from left to right ; If the current character is not present in B ; Subtract the total possible substrings ; Update the value of lastpos to current index ; Print the final answer ; Given String ; Given character array ; Function call
def numberofsubstrings ( str , k , charArray ) : NEW_LINE INDENT N = len ( str ) NEW_LINE available = [ 0 ] * 26 NEW_LINE for i in range ( 0 , k ) : NEW_LINE INDENT available [ ord ( charArray [ i ] ) - ord ( ' a ' ) ] = 1 NEW_LINE DEDENT lastPos = - 1 NEW_LINE ans = ( N * ( N + 1 ) ) / 2 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( available [ ord ( str [ i ] ) - ord ( ' a ' ) ] == 0 ) : NEW_LINE INDENT ans -= ( ( i - lastPos ) * ( N - i ) ) NEW_LINE lastPos = i NEW_LINE DEDENT DEDENT print ( int ( ans ) ) NEW_LINE DEDENT str = " abcb " NEW_LINE k = 2 NEW_LINE charArray = [ ' a ' , ' b ' ] NEW_LINE numberofsubstrings ( str , k , charArray ) NEW_LINE