[leetcode]Longest Substring with At Most K Distinct Characters

时间:2020-01-31 15:49:02   收藏:0   阅读:57

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

  

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!