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
function numberofsubstrings ( str , k , charArray ) { var N = str . length ; var available = [ 26 ] ; for ( var i = 0 ; i < k ; i ++ ) { available [ charArray [ i ] - ' ' ] = 1 ; } var lastPos = - 1 ; var ans = ( N * ( N + 1 ) ) / 2 ; for ( var i = 0 ; i < N ; i ++ ) { if ( available [ str . charAt ( i ) - ' ' ] == 0 ) { ans -= ( ( i - lastPos ) * ( N - i ) ) ; lastPos = i ; } } document . write ( ans ) ; } var str = " " ; var k = 2 ; var charArray = [ ' ' , ' ' ] ; numberofsubstrings ( str , k , charArray ) ;