Python sliding window with two two pointers.


  • 0
    B
    class Solution(object):
        def lengthOfLongestSubstringTwoDistinct(self, s):
            """
            :type s: str
            :rtype: int
            """
            if len(s) == 0 : return 0
            
            hashmap = {}
            maxlength = 0
            leftp = 0
    
            for j in range(0,len(s),1):
                if s[j] not in hashmap:
                        hashmap[s[j]] = 1
                else: hashmap[s[j]] += 1
                while len(hashmap) > 2:
                        hashmap[s[leftp]] -= 1
                        if hashmap[s[leftp]] == 0:
                            hashmap.pop(s[leftp])
                        leftp += 1
                strlength = j - leftp +1
                if strlength > maxlength:
                    maxlength = strlength
            
            return maxlength

Log in to reply
 

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