Longest Substring with At Most Two Distinct Characters

双指针,但是这道题有个巨坑就是关于重复字母数字的统计,因为这里要的是不多于,所以很有可能出现跳出循环时,是因为重复字母多了跳出,也可能是因为快指针到头了跳出,但是还有一种可能是快指针到了头,重复数字这时也正好多了的情况,所以这里只能通过一个if else语句去把这三件事判断清楚,先是一个用dict版本的,因为有del关键字,速度算是很慢的

class Solution(object):
    def lengthOfLongestSubstringTwoDistinct(self, s):
        """
        :type s: str
        :rtype: int
        """
        n = len(s)
        counter = collections.Counter()
        result = 0
        cur = 0

        for i in xrange(n):
            while cur < n and len(counter.keys()) <= 2:
                counter[s[cur]] += 1
                cur += 1

            if len(counter.keys()) > 2:
                result = max(result, cur - i - 1)
            else:
                result = max(result, cur - i)
            counter[s[i]] -= 1
            if counter[s[i]] == 0:
                del counter[s[i]]

        return result

results matching ""

    No results matching ""