您的位置:首页 > 其它

Leetcode: Longest Substring with At Most Two Distinct Characters

2015-11-04 05:58 423 查看

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

[code]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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: