Longest Substring with At Most K Distinct Characters
Given a string s, find the length of the longest substring T that contains at most k distinct characters.
Example
For example, Given s = "eceba", k = 3,
T is "eceb" which its length is 4.
Notes:
- Forward two pointers
- inner loop: size to k (break when size == k and !map.containksKey(c))
- template: out loop -> inner loop -> max -> remove i
public int lengthOfLongestSubstringKDistinct(String s, int k) {
if (s == null || s.isEmpty() || k <= 0) {
return 0;
}
int n = s.length();
int j = 0;
int max = 0;
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < n; ++i) {
while(j < n) {
char c = s.charAt(j);
if (map.containsKey(c)) {
map.put(c, map.get(c)+1);
} else {
if (map.size() == k) {
break;
}
map.put(c, 1);
}
j++;
}
max = Math.max(max, j-i);
char c = s.charAt(i);
int num = map.get(c);
if (num == 1) {
map.remove(c);
} else {
map.put(c, num-1);
}
}
return max;
}