text: Count of substrings formed using a given set of characters only | C # program for the above approach ; 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 ; Driver Code ; Given String ; Given character array ; Function Call
code: using System ; class GFG { public static void numberofsubstrings ( String str , int k , char [ ] charArray ) { int N = str . Length ; int [ ] available = new int [ 26 ] ; for ( int i = 0 ; i < k ; i ++ ) { available [ charArray [ i ] - ' a ' ] = 1 ; } int lastPos = - 1 ; int ans = ( N * ( N + 1 ) ) / 2 ; for ( int i = 0 ; i < N ; i ++ ) { if ( available [ str [ i ] - ' a ' ] == 0 ) { ans -= ( ( i - lastPos ) * ( N - i ) ) ; lastPos = i ; } } Console . WriteLine ( ans ) ; } public static void Main ( String [ ] args ) { String str = " abcb " ; int k = 2 ; char [ ] charArray = { ' a ' , ' b ' } ; numberofsubstrings ( str , k , charArray ) ; } }