My code:
public class Solution {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
if (s == null || s.length() == 0) {
return 0;
}
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int i = 0;
int j = 0;
int maxLen = 0;
for (; i < s.length(); i++) {
char curr = s.charAt(i);
map.put(curr, i);
if (map.size() > k) {
int leftMost = Integer.MAX_VALUE;
for (Character c : map.keySet()) {
leftMost = Math.min(leftMost, map.get(c));
}
map.remove(s.charAt(leftMost));
j = leftMost + 1;
}
maxLen = Math.max(maxLen, i - j + 1);
}
return maxLen;
}
}
和 Longest Substring with At Most Two Distinct Characters
一个原理。
不赘述了。
Similar Questions#
Longest Substring with At Most K Distinct Characters
Longest Substring with At Most Two Distinct Characters
Longest Substring Without Repeating Characters
Anyway, Good luck, Richardo! — 09/18/2016