Count of substrings formed using a given set of characters only | Java 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
import java . util . Arrays ; class GFG { public static void numberofsubstrings ( String str , int k , char charArray [ ] ) { int N = str . length ( ) ; int available [ ] = new int [ 26 ] ; Arrays . fill ( available , 0 ) ; 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 . charAt ( i ) - ' a ' ] == 0 ) { ans -= ( ( i - lastPos ) * ( N - i ) ) ; lastPos = i ; } } System . out . println ( ans ) ; } public static void main ( String args [ ] ) { String str = " abcb " ; int k = 2 ; char [ ] charArray = { ' a ' , ' b ' } ; numberofsubstrings ( str , k , charArray ) ; } }