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(k == 0 || s.empty()) return 0 ;
int left = 0 , right = 0 ;
int res = 0 ;
unordered_map<char , int> ctimes ;
while((right == -1 || left <= right) && right < s.size())
{
while(right < s.size() && ctimes.size() <= k)
{
right++ ;
ctimes[s[right]]++ ;
}
res = max(res , right - left) ;
while(left <= right && ctimes.size() > k)
{
ctimes[s[left]]-- ;
if(ctimes[s[left]] == 0) ctimes.erase(s[left]) ;
left++ ;
}
}
return res ;
}
};
错误一:
"ab"
1
2
1
一直纠结在left<=right 或者 left < right 上 , right++后忘记判断right < s.size()
当k == 1 时,left确实有==right的可能,因为是先将s[left]从ctimes中去掉 后left++就满足了left<=right
class Solution {
public:
int lengthOfLongestSubstringKDistinct(string s, int k)
{
if(k == 0 || s.empty()) return 0 ;
int left = 0 , right = 0 ;
int res = 0 ;
unordered_map<char , int> ctimes ;
ctimes[s[0]]++ ;
while(left <= right && right < s.size())
{
while(right < s.size() && ctimes.size() <= k)
{
right++ ;
if(right < s.size()) ctimes[s[right]]++ ;
}
res = max(res , right - left) ;
while(left <= right && ctimes.size() > k)
{
ctimes[s[left]]-- ;
if(ctimes[s[left]] == 0) ctimes.erase(s[left]) ;
left++ ;
}
}
return res ;
}
};