l28 Weighted Substring
l28 Weighted Substring
INTRODUCTION
▪ The problem of counting the substrings from a given
string with the sum of weights at most K.
▪ To implement the problem statement we consider a
string S to generate substrings and some value for k.
▪ The character weights are predefined integer values
and we consider some value of K like 2, 3 or anything.
▪ We count only those substrings whose total weight is
equal to the value of K.
The weights of the characters are defined in two different
ways:
• When the weights are defined for a string in any order.
• When the weights are defined in alphabetical order starting from
1.
EXAMPLE:
String = "aba“
K = 5
OUTPUT:
The possible substrings with their weights at most 5 is : 6
Explanation:
Using the input string and the value of k, we take the weights
of the characters in alphabetical order starting with 1.
The weight of 'a' is 1, 'b' is 2, 'c' is 3, 'd' is 4, and so on. There
are 6 possible substrings with a sum of weights at most K.
The substrings are as follows −
1."a" (Weight = 1)
2."b" (Weight = 2)
3."a" (Weight = 1)
4."ab" (Weight = 3)
5."ba" (Weight = 3)
6."aba" (Weight = 4)
ALGORITHM:
• Initialize the input string.
• Consider the weight of the characters in alphabetical order
starting from 1.
• Initialize the value of k(maximum possible weight).
• Iterate through all substrings whose weight is at most equal to
k.
• The counter variable counts all substrings with weights at most
k.
• Print the result of the k.
CODING:
import java.util.Scanner;
scanner.close();
}
}
OUTPUT:
Enter the input string: hello
Enter the maximum possible weight (k) : 10
Number of substrings with weight at most 10: 15
THANK YOU