General k distinct characters solution in python

  • 0

    The main idea is that using OrderedDict to save the last index current char appeared, and make the index in the OrderedDict ascendingly. When the length of OrderedDict is larger than K, move start to OrderedDict.first.val + 1 and remove OrderedDict.first.

    class Solution(object):
        def lengthOfLongestSubstringTwoDistinct(self, s):
            queue, start, r, k = collections.OrderedDict(), 0, 0, 2
            for i, char in enumerate(s):
                if char in queue:
                queue[char] = i
                if len(queue) > k:
                    start = queue.popitem(False)[1] + 1
                r = max(r, i - start + 1)
            return r

Log in to reply

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