码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]Longest Substring with At Most K Distinct Characters

时间:2020-01-31 15:49:02      阅读:57      评论:0      收藏:0      [点我收藏+]

标签:substring   most   lse   highlight   str   +=   longest   code   tin   

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

标签:substring   most   lse   highlight   str   +=   longest   code   tin   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!