Count of all sub | C # 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
using System ; using System . Collections . Generic ; 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 [ j ] - ' a ' ; sum += Q [ pos ] - '0' ; s += P [ j ] ; if ( sum <= K ) { S . Add ( s ) ; } else { break ; } } } return S . Count ; } static void Main ( ) { string S = " abcde " ; string W = "12345678912345678912345678" ; int K = 5 ; int N = S . Length ; Console . WriteLine ( distinctSubstring ( S , W , K , N ) ) ; } }