Given a string, find the length of the longest substring T that contains at most k distinct characters.
Example 1:
Input: s = "eceba", k = 2
Output: 3
Explanation: T is "ece" which its length is 3.
Example 2:
Input: s = "aa", k = 1
Output: 2
Explanation: T is "aa" which its length is 2.
class Solution {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
if (s == null || s.length () == 0 || k == 0)
return 0;
Map<Character, Integer> tracker = new HashMap<> ();
int start = 0;
int end = 0;
int maxLen = 0;
while (end < s.length ()) {
char currentCh = s.charAt (end);
int freq = tracker.getOrDefault (currentCh, 0) + 1;
tracker.put (currentCh, freq);
if (tracker.size () <= k) {
maxLen = Math.max (maxLen, end - start + 1);
end++;
continue;
}
while (start <= end && tracker.size () > k) {
char startCh = s.charAt (start);
freq = tracker.get (startCh) - 1;
if (freq == 0) {
tracker.remove (startCh);
} else {
tracker.put (startCh, freq);
}
start ++;
}
end ++;
}
return maxLen;
}
}
网友评论