题目描述
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.
解题思路
【C++】
class Solution {
public:
int lengthOfLongestSubstringKDistinct(string s, int k) {
unordered_map<char, int> hash;
int left = 0, right = 0, Max = 0;
while (right < s.size()) {
hash[s[right++]++;
while (hash.size() > k) {
hash[s[left]]--;
if (hash[s[left]] == 0) {hash.erase(s[left]);}
left++;
}
Max = max(Max, right - left);
}
return Max;
}
};
【Java】
class Solution {
public:
public int lengthOfLongestSubstringKDistinct(String s, int k) {
Map<Character, Integer> hash = new HashMap<>();
int left = 0, right = 0, Max = 0;
while (right < s.length()) {
hash.put(s.charAt(right), ++hash.get(s.charAt(right++)));
while (hash.size() > k) {
hash.put(s.charAt(left), --hash.get(s.charAt(left)));
if (hash.get(s.charAt(left)) == 0) {hash.remove(s.charAt(left));}
left++;
}
Max = Math.max(Max, right - left);
}
return Max;
}
}
参考文献