Count all sub | C ++ 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
#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 P = " abcde " ; string Q = "12345678912345678912345678" ; int K = 5 ; int N = P . length ( ) ; cout << distinctSubstring ( P , Q , K , N ) ; return 0 ; }