Count all sub | 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
def distinctSubstring ( P , Q , K , N ) : NEW_LINE INDENT S = set ( ) NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT sum = 0 ; NEW_LINE s = ' ' NEW_LINE for j in range ( i , N ) : NEW_LINE INDENT pos = ord ( P [ j ] ) - 97 NEW_LINE sum = sum + ord ( Q [ pos ] ) - 48 NEW_LINE s += P [ j ] NEW_LINE if ( sum <= K ) : NEW_LINE INDENT S . add ( s ) NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT return len ( S ) NEW_LINE DEDENT P = " abcde " NEW_LINE Q = "12345678912345678912345678" NEW_LINE K = 5 NEW_LINE N = len ( P ) NEW_LINE print ( distinctSubstring ( P , Q , K , N ) ) NEW_LINE