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.
Companies:
Facebook, Amazon, Google
Related Topics:
Hash Table, String, Sliding Window
Similar Questions:
- Longest Substring Without Repeating Characters (Medium)
- Longest Substring with At Most Two Distinct Characters (Hard)
- Longest Repeating Character Replacement (Medium)
- Subarrays with K Different Integers (Hard)
- Max Consecutive Ones III (Medium)
// OJ: https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
int lengthOfLongestSubstringKDistinct(string s, int k) {
vector<int> m(128, 0);
int i = 0, j = 0, ans = 0, cnt = 0;
while (j < s.size()) {
if (m[s[j++]]++ == 0) cnt++;
while (cnt > k) {
if (m[s[i++]]-- == 1) cnt--;
}
ans = max(ans, j - i);
}
return ans;
}
};