Longest Substring with At Most K Distinct Characters
Question (LC.340)
Example
I: s = "eceba", k = 2
O: 3 because "ece"
I: s = "eceba", k = 3
O: 4 bacause "eceb"Analysis
Brute Force Approach
func longestSubKD(str, k)
if s == null || len(s) == 0
return 0
int maxLenght = 0
Set<Character> charSet = new HashSet
for i from 0 to len(s)
charSet.clear()
for j from i to len(s) and charSet.size() <= k // comment
charSet.add(str.charAt(j))
end for
maxLength = Math.max(maxLength, j-i)
// since the for loop breaks after the condition becomes false
// (one step beyond the constraint), j-i+1 the +1 is omitted
end for
return maxLength
end funcHow For Loop Works
Brute Force Code
Sliding Window Approach
Sliding Window Code
Complexity
Follow Up
Last updated