Skip to content

159 Longest Substring with At Most Two Distinct Characters

159. Longest Substring with At Most Two Distinct Characters

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

难度 : Hard

class Solution(object):
    def lengthOfLongestSubstringTwoDistinct(self, s):
        """
        :type s: str
        :rtype: int
        """
        maps = {}
        begin, end, counter, length = 0, 0, 0, 0
        while end < len(s):
            maps[s[end]] = maps.get(s[end], 0) + 1
            if maps[s[end]] == 1:
                counter += 1
            end += 1   # end 永远指向下一个待处理的字符
            while counter > 2:
                maps[s[begin]] -= 1
                if maps[s[begin]] == 0:
                    counter -= 1
                begin += 1
            length = max(length, end - begin) # 因此这里是```end - begin```而不是```end - begin + 1```
        return length


回到顶部