Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
531 B
3
Indexable
Never
int lengthOfLongestSubstringKDistinct(string s, int k) {
	map<char, int> m;
	int ans = 0;
	int j = 0;
	for(int i=0; i<s.size(); ++i)
	{
		// adding the ith character to my substring
		m[s[i]]++;

		// if m.size() > k that means there are more than k unique characters in the window [j ... i]

		while(m.size() > k)
		{
			// removing the jth character
			m[s[j]]--;	
			if(m[s[j]] == 0)
			{
				m.erase(s[j]);
			}
			//reducing the window size
			++j;
		}

		ans = max(ans, i - j + 1);
	}
	return ans;
}