5/01/2021

[LeetCode] 159. Longest Substring with At Most Two Distinct Characters

 Problem :  https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/

This is a classic sliding window problem.


class Solution:
    def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
        seen = defaultdict(int)
        distinct = 0
        result = 0
        
        right = 0
        
        for left in range(len(s)):
            while right < len(s) and distinct <= 2:
                seen[s[right]] += 1
                
                if seen[s[right]] == 1:
                    distinct += 1
                
                right += 1
                
                if distinct <= 2:
                    result = max(result, right - left)
             
            seen[s[left]] -= 1
            if seen[s[left]] == 0:
                distinct -= 1
                
        return result

No comments:

Post a Comment