8.19 - hard - 71

340. Longest Substring with At Most K Distinct Characters

这题是典型的前向型指针的模板题

class Solution(object):
   def lengthOfLongestSubstringKDistinct(self, s, k):
       """
       :type s: str
       :type k: int
       :rtype: int
       """
       if k == 0:
           return 0
       hash = {}
       j = 0
       counter = 0
       res = 0
       for i in range(len(s)):
           while j < len(s) and (s[j] in hash or counter < k):
               if s[j] in hash:
                   hash[s[j]] += 1
               else:
                   hash[s[j]] = 1
                   counter += 1
               res = max(res, j-i+1)
               j += 1
           hash[s[i]] -= 1
           if hash[s[i]] == 0:
               hash.pop(s[i], 0)
               counter -= 1
       
       return res
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容