Medium Longest Substring with At Most K Distinct Characters
26%
Accepted
Given a string s, find the length of the longest substring T that contains at most k distinct characters.
Example
For example, Given s = "eceba"
, k = 3
,
T is "eceb"
which its length is 4
.
Challenge
O(n), n is the size of the string s.
class Solution {
public:
/**
* @param s : A string
* @return : The length of the longest substring
* that contains at most k distinct characters.
*/
//ecebbbbdf
//eebcaaad
int lengthOfLongestSubstringKDistinct(string s, int k) {
// write your code here
if (k<=0)
return 0;
if (s.size() < k)
return 0;
map<char, int> myMap;
int curStart = 0;
int curEnd = 0;
int maxStart = 0;
int maxEnd = 0;
int idx = 0;
bool found = false;
for (int idx=0; idx< s.size(); idx++)
{
if (myMap.count(s.at(idx)) == 0)
{
myMap[s.at(idx)] = 1;
if (myMap.size() > k)
{
if (curEnd-curStart > maxEnd-maxStart)
{
maxStart = curStart;
maxEnd = curEnd;
}
while (myMap.size() > k)
{
myMap[s.at(curStart)]--;
if (myMap[s.at(curStart)] == 0)
{
myMap.erase(s.at(curStart));
}
curStart++;
}
}
}
else
{
myMap[s.at(idx)]++;
}
curEnd = idx;
}
if (curEnd-curStart > maxEnd-maxStart)
{
maxStart = curStart;
maxEnd = curEnd;
}
return maxEnd-maxStart+1;
}
};