LeetCode 340 Longest Substring with At Most K Distinct Characters

LeetCode 340 Longest Substring with At Most K Distinct Characters Problem

Download Code
class Solution(object):
    def lengthOfLongestSubstringKDistinct(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: int
        """
        count = [0] * 256
        i, numDistinct, maxLen = 0, 0, 0
        for j in range(len(s)):
            # udpate j
            if count[ord(s[j])] == 0:
                numDistinct += 1
            count[ord(s[j])] += 1
            # udpate i
            while numDistinct > k:
                count[ord(s[i])] -= 1
                if count[ord(s[i])] == 0:
                    numDistinct -= 1
                i += 1
            maxLen =  max(j - i + 1, maxLen)
        return maxLen
Download Longest Substring with At Most K Distinct Characters.py

List of all Longest Substring with At Most K Distinct Characters problems

Leetcode 340 Longest Substring with At Most K Distinct Characters problem solution in python3 with explanation. This is the best place to expand your knowledge and get prepared for your next interview.

Feedback is the most important part of any website.

If you have any query, suggestion or feedback, Please feel free to contact us.