Count of all sub | Java implementation to count all sub - strings with sum of weights at most K ; Function to count all substrings ; Hashmap to store substrings ; Iterate over all substrings ; Variable to maintain sum of all characters encountered ; Variable to maintain substring till current position ; Get position of character in string W ; Add weight to current sum ; Add current character to substring ; Check if sum of characters is <= K insert in Hashmap ; Driver Code ; Initialise string ; Initialise weight
import java . io . * ; import java . util . * ; class GFG { static int distinctSubstring ( String P , String Q , int K , int N ) { Set < String > S = new HashSet < > ( ) ; for ( int i = 0 ; i < N ; ++ i ) { int sum = 0 ; String s = " " ; for ( int j = i ; j < N ; ++ j ) { int pos = P . charAt ( j ) - ' a ' ; sum += Q . charAt ( pos ) - '0' ; s += P . charAt ( j ) ; if ( sum <= K ) { S . add ( s ) ; } else { break ; } } } return S . size ( ) ; } public static void main ( String args [ ] ) { String S = " abcde " ; String W = "12345678912345678912345678" ; int K = 5 ; int N = S . length ( ) ; System . out . println ( distinctSubstring ( S , W , K , N ) ) ; } }