Count of all sub | 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
def distinctSubstring ( P , Q , K , N ) : NEW_LINE INDENT S = set ( ) NEW_LINE for i in range ( 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 += 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 if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " abcde " NEW_LINE W = "12345678912345678912345678" NEW_LINE K = 5 NEW_LINE N = len ( S ) NEW_LINE print ( distinctSubstring ( S , W , K , N ) ) NEW_LINE DEDENT