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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int distinctSubstring ( string & P , string & Q , int K , int N ) { unordered_set < string > S ; 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 . insert ( s ) ; } else { break ; } } } return S . size ( ) ; } int main ( ) { string S = " abcde " ; string W = "12345678912345678912345678" ; int K = 5 ; int N = S . length ( ) ; cout << distinctSubstring ( S , W , K , N ) ; return 0 ; }