首页 > 其他 > 详细

[leetcode]Longest Substring with At Most K Distinct Characters

时间:2020-01-31 16:54:56      阅读:101      评论:0      收藏:0      [点我收藏+]

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

  

[leetcode]Longest Substring with At Most K Distinct Characters

原文:https://www.cnblogs.com/lautsie/p/12245564.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!