Leetcode: Longest Substring with At Most Two Distinct Characters

Question

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

For example, Given s = “eceba”,

T is “ece” which its length is 3.

Hide Company Tags Google
Hide Tags Hash Table Two Pointers String
Hide Similar Problems


Solution

Get idea from here1, here2

Using sliding window method

class Solution(object):
    def lengthOfLongestSubstringTwoDistinct(self, s):
        """
        :type s: str
        :rtype: int
        """

        s = list(s)

        start, res = 0,0
        dict_c = {}
        for cur,c in enumerate(s):
            if c in dict_c:
                dict_c[c] += 1
            else: 
                # new char
                while len(dict_c.keys())>1:    # make sure there is only one char in the window before c
                    if dict_c[ s[start] ]==1:
                        del dict_c[ s[start] ]
                    else:
                        dict_c[ s[start] ] -= 1
                    start += 1

                dict_c[c] = 1

            res = max(res, cur-start+1)  # have to update res no matter what happens

        return res

你可能感兴趣的:(leetcode)