159. Longest Substring with At Most Two Distinct Characters

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

Given a string s , find the length of the longest substring t  that contains at most 2 distinct characters.

Example 1:

Input: "eceba"
Output: 3
Explanation: t is "ece" which its length is 3.

Example 2:

Input: "ccaabbb"
Output: 5
Explanation: t is "aabbb" which its length is 5.
class Solution(object):
    def lengthOfLongestSubstringTwoDistinct(self, s):
        """
        :type s: str
        :rtype: int
        
        Worst case time and space complexity:
        Time: O(N), Space: O(W) where N is size of string and W is size of max window
        """
        # Initialize sliding window and counts of chars in the window
        left = 0
        right = 0
        counts = collections.defaultdict(int)
        
        # Slide the window down the string until we reach the end
        #
        # Loop invariant:
        # (1) The previously seen window is s[left:right]
        # (2) The right index - left index of window is always the length
        #     of the longest substring with <= 2 distinct characters
        while right < len(s):
            # Slide the right end up and update counts such that the window is now s[left:right+1]
            counts[s[right]] += 1
            right += 1
            
            # If the window has more than 2 characters, slide the left end of 
            # the window up and update counts such that the window is now s[left+1:right+1]
            if len(counts) > 2:
                counts[s[left]] -= 1
                if not counts[s[left]]:
                    del counts[s[left]]
                left += 1

        # The length of the window is the length of the longest valid substring
        return right - left
        
        

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值