Simple Python 3 solution


  • 0
    A
    class Solution:
        def lengthOfLongestSubstringTwoDistinct(self, s):
            """
            :type s: str
            :rtype: int
            """
            queue = []
            ans = 0
            last_map = {}
            start_i = 0
            for i in range(len(s)):
                if s[i] in queue:
                    queue.remove(s[i])
                queue.append(s[i])
                last_map[s[i]] = i
                if len(queue) > 2:
                    to_del = queue.pop(0)
                    start_i = last_map[to_del] + 1
                ans = max(ans, i - start_i + 1)
            return ans
    

Log in to reply
 

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