![]() |
VOOZH | about |
Given a string S, an integer K and set of characters Q[], the task is to find the longest substring in string S which contains atmost K characters from the given character set Q[].
Examples:
Input: S = "normal", Q = {"a", "o", "n", "m", "r", "l"}, K = 1
Output: 1
Explanation:
All the characters in the given string S are present in array.
Therefore, we can select any substring of length 1.
Input: S = "giraffe", Q = {"a", "f", "g", "r"}, K = 2
Output : 3
Explanation:
Possible substrings with atmost 2 characters
From the given set are {"gir", "ira", "ffe"}
The maximum length of all the substrings is 3.
Approach: The idea is to use the concept of two pointers to consider the substrings of maximum length, such that it contains at most K character from the given set. Below is the illustration of the approach:
cur_max = max(cur_max, right - left)
Below is the implementation of the above approach:
3
Performance Analysis: