Demo entry 6783861

substring

   

Submitted by anonymous on Feb 22, 2019 at 21:20
Language: Java. Code size: 989 Bytes.

class Solution:
    # @param s : A string
    # @return : An integer
    def lengthOfLongestSubstringKDistinct(self, s, k):
        # write your code here
        if not s or not k:
            return 0
        if len(s) < k:
            return len(s)
        right, length = 0, 0
        sourceHash = {}
        for left in range(len(s)):
            while len(sourceHash) <= k and right < len(s):
                if s[right] not in sourceHash:
                    sourceHash[s[right]] = 1
                else:
                    sourceHash[s[right]] += 1
                right += 1
            if len(sourceHash) == k + 1 and right - left - 1 > length:
                length = right - left - 1
            elif right >= len(s) and right - left > length:
                length = right - left
                
            sourceHash[s[left]] -= 1
            if sourceHash[s[left]] == 0:
                del sourceHash[s[left]]
        
        return length

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).