Skip to content

Latest commit

 

History

History
23 lines (21 loc) · 605 Bytes

159.md

File metadata and controls

23 lines (21 loc) · 605 Bytes
  • time: O(n)
  • space: O(1)
class Solution:
    def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
        n = len(s)
        if n < 3: return n
        left, right = 0,0
        maxLength = 2
        hash = collections.defaultdict()
        while right < n:
            if len(hash) < 3:
                hash[s[right]] = right
                right += 1
            if len(hash) ==3 :
                toDelIdx = min(hash.values())
                del hash[s[toDelIdx]]
                left = toDelIdx+1
            maxLength = max(maxLength, right-left)
        return maxLength