340.Longest Substring With at Most K Distinct Characters
Given a string, find the length of the longest substring T that contains at most k distinct characters.
For example, Given s = “eceba” and k = 2,
T is “ece” which its length is 3.
O(n) time O(k) space HashTable solution
public class Solution {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
if (s == null || s.length() == 0 || k == 0) {
return 0;
}
int max = 0, left = 0;
HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char cur = s.charAt(i);
map.put(cur, map.getOrDefault(cur, 0) + 1);
while (map.size() > k) {
char leftChar = s.charAt(left);
if (map.containsKey(leftChar)) {
map.put(leftChar, map.get(leftChar) - 1);
if (map.get(leftChar) == 0) {
map.remove(leftChar);
}
}
left++;
}
max = Math.max(max, i - left + 1);
}
return max;
}
}