# 159. Longest Substring with At Most Two Distinct Characters

Given a string  s  , find the length of the longest substring  t that contains at most 2 distinct characters.

Example 1:

``````Input: "eceba"
Output: 3
Explanation: _t_ is "ece" which its length is 3.
``````

Example 2:

``````Input: "ccaabbb"
Output: 5
Explanation: _t_ is "aabbb" which its length is 5.
``````

``````class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
int res = 0, left = 0;
unordered_map<char, int> m;
for (int i = 0; i < s.size(); ++i) {
++m[s[i]];
while (m.size() > 2) {
if (--m[s[left]] == 0) m.erase(s[left]);
++left;
}
res = max(res, i - left + 1);
}
return res;
}
};
``````

``````class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
int res = 0, left = 0;
unordered_map<char, int> m;
for (int i = 0; i < s.size(); ++i) {
m[s[i]] = i;
while (m.size() > 2) {
if (m[s[left]] == left) m.erase(s[left]);
++left;
}
res = max(res, i - left + 1);
}
return res;
}
};
``````

1. 若当前字符和前一个字符相同，继续循环。

2. 若不同，看当前字符和 right 指的字符是否相同

(1) 若相同，left 不变，右边跳到 i - 1

(2) 若不同，更新结果，left 变为 right+1，right 变为 i - 1

``````class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
int left = 0, right = -1, res = 0;
for (int i = 1; i < s.size(); ++i) {
if (s[i] == s[i - 1]) continue;
if (right >= 0 && s[right] != s[i]) {
res = max(res, i - left);
left = right + 1;
}
right = i - 1;
}
return max(s.size() - left, res);
}
};
``````

``````class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
int res = 0, cur = 0, cntLast = 0;
char first, second;
for (char c : s) {
cur = (c == first || c == second) ? cur + 1 : cntLast + 1;
cntLast = (c == second) ? cntLast + 1 : 1;
if (c != second) {
first = second; second = c;
}
res = max(res, cur);
}
return res;
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/159

Longest Substring Without Repeating Characters

Sliding Window Maximum

Longest Substring with At Most K Distinct Characters

Subarrays with K Different Integers

https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/

https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/discuss/49759/Share-my-c%2B%2B-solution

https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/discuss/49682/Simple-O(n)-java-solution-easily-extend-to-k-characters

https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/discuss/49708/Sliding-Window-algorithm-template-to-solve-all-the-Leetcode-substring-search-problem.

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation