Skip to content

Latest commit

 

History

History
 
 

159. Longest Substring with At Most Two Distinct Characters

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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:

Solution 1. Sliding Window

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;
    }
};

Discuss

https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/discuss/1499839/C%2B%2B-Sliding-Window-(%2B-Cheat-Sheet)