Count all sub | Java program to find the count of all the sub - Strings with weight of characters atmost K ; Function to find the count of all the subStrings with weight of characters atmost K ; Hashmap to store all subStrings ; Iterate over all subStrings ; Maintain the sum of all characters encountered so far ; Maintain the subString till the current position ; Get the position of the character in String Q ; Add weight to current sum ; Add current character to subString ; If sum of characters is <= K then insert in into the set ; Finding the size of the set ; Driver code
import java . util . * ; class GFG { static int distinctSubString ( String P , String Q , int K , int N ) { HashSet < String > S = new HashSet < String > ( ) ; 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 P = " abcde " ; String Q = "12345678912345678912345678" ; int K = 5 ; int N = P . length ( ) ; System . out . print ( distinctSubString ( P , Q , K , N ) ) ; } }