Question: You are given a string s and an integer k. Write a function Exercise7(s,k) that returns the length of the longest substring of s that
You are given a string s and an integer k. Write a function Exercise7(s,k) that returns the length of the longest substring of s that contains at most k distinct characters. Mark: [10%] Example 1: Input: s = "eceba", k = 2 Output: 3 Explanation: The substring is "ece" with length 3. Example 2: Input: s = "aa", k = 1 Output: 2 Explanation: The substring is "aa" with length 2. Hint: To solve this problem in one pass, you need to use sliding window approach with two set pointers left and right serving as the window boundaries. The plan is that you set both pointers in the position 0 and then move right pointer to the right while the window contains not more than k distinct characters. If at some point you got k + 1 distinct characters, then you may increase left pointer to keep not more than k + 1 distinct characters in the window.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
