Given a string s
, return the length of the longest substring that contains at most two distinct characters.
Example 1:
Input: s = "eceba" Output: 3 Explanation: The substring is "ece" which its length is 3.
Example 2:
Input: s = "ccaabbb" Output: 5 Explanation: The substring is "aabbb" which its length is 5.
Constraints:
1 <= s.length <= 105
s
consists of English letters.
Companies:
Yandex
Related Topics:
Hash Table, String, Sliding Window
Similar Questions:
- Longest Substring Without Repeating Characters (Medium)
- Sliding Window Maximum (Hard)
- Longest Substring with At Most K Distinct Characters (Medium)
- Subarrays with K Different Integers (Hard)
Check out "C++ Maximum Sliding Window Cheatsheet Template!".
Shrinkable Sliding Window:
// OJ: https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(C)
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
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 > 2) {
if (m[s[i++]]-- == 1) --cnt;
}
ans = max(ans, j - i);
}
return ans;
}
};
Non-shrinkable Sliding Window:
// OJ: https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(C)
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
int distinct = 0, cnt[128] = {}, N = s.size(), i = 0, j = 0;
while (j < N) {
distinct += ++cnt[s[j++]] == 1;
if (distinct > 2) distinct -= --cnt[s[i++]] == 0;
}
return j - i;
}
};