[leetcode]Longest Substring with At Most K Distinct Characters

Python3,双指针,注意K为0的情况。

class Solution:
    def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
        if k == 0:
            return 0
        charMap = {}
        result = 0
        i = j = 0
        while j < len(s):
            if s[j] in charMap:
                charMap[s[j]] += 1
                j += 1
            elif len(charMap) < k:
                charMap[s[j]] = 1
                j += 1
            else:
                if j - i > result:
                    result = j - i
                charMap[s[i]] -= 1
                if charMap[s[i]] == 0:
                    del charMap[s[i]]
                i += 1
        if j - i > result:
            result = j - i
        return result

  

posted @ 2020-01-31 15:39  阿牧遥  阅读(186)  评论(0编辑  收藏  举报