10 lines python solution O(n) with two pointers


  • 1
    Y
        def lengthOfLongestSubstringKDistinct(self, s, k):
            d, start, res = dict(), 0, 0
            for i, c in enumerate(s):
                d[c] = i
                while len(d) > k:
                    if d[s[start]] == start:
                        d.pop(s[start])
                    start += 1
                res = max(res, i - start + 1)
            return res
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.