/*Sliding Window*/
public class Solution {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
int[] count = new int[256];
int num = 0, i = 0, res = 0;
for (int j = 0; j < s.length(); j++) {
if (count[s.charAt(j)]++ == 0) num++;
if (num > k) {
while (--count[s.charAt(i++)] > 0);
num--;
}
res = Math.max(res, j - i + 1);
}
return res;
}
}
public class Solution {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
Map<Character, Integer> map = new HashMap<>();
int res = 0;
int start = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (map.size() <= k) {
map.put(c, i);
}
if (map.size() > k) {
int leftMost = s.length();
for (int idx : map.values()) {
leftMost = Math.min(leftMost, idx);
}
start = leftMost + 1;
map.remove(s.charAt(leftMost));
}
res = Math.max(res, i - start + 1);
}
return res;
}
}