Longest Substring with at most K distinct characters

还是哈希表加双指针就可以了

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

        for i in xrange(n):
            while cur < n and len(sCounter) <= k:
                sCounter[s[cur]] += 1
                cur += 1

            if len(sCounter) > k:
                result = max(result, cur - i)    
            else:
                result = max(result, cur - i + 1)
                if cur >= n:
                    break

            sCounter[s[i]] -= 1
            if not sCounter[s[i]]:
                sCounter.pop(s[i])

        return result

results matching ""

    No results matching ""