[leetcode]Longest Substring with At Most K Distinct Characters

Posted 阿牧遥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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

  

以上是关于[leetcode]Longest Substring with At Most K Distinct Characters的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode409. Longest Palindrome

leetcode:longest-increasing

[Leetcode]Longest Palindromic Substring

leetcode longest consecutive sequence

LeetCode Longest Increasing Subsequence

#Leetcode# 14. Longest Common Prefix