Python straightforward solution, easy to understand


  • 0
    P

    first and second are two characters currently tracked.
    fc and sc are counters for first and second separately
    temp is the counter for mostly recently tracked character

    class Solution(object):
        def lengthOfLongestSubstringTwoDistinct(self, s):
            """
            :type s: str
            :rtype: int
            """
            if len(s) <= 2 or len(set(s)) <= 2:
            	return len(s)
            first, second, fc, sc, temp = s[0], None, 1, 0, 1
            res = 1
            for c in s[1:]:
            	# print("first:{}:{} - second:{}:{} - res:{}".format(first,fc,second,sc,res))
            	if second is None:
            		if c == first:
    	        		fc += 1
    	        	else:
    	        		second, sc, temp = c, 1, 1
    	        		res = max(res, fc + sc)
    	        	continue
            	if c == second:
            		sc += 1
            		temp += 1
                    # if c == first, then we need to swap first and second, and reset temp
            	elif c == first:
            		first, second, fc, sc, temp = second, first, sc, fc + 1, 1
                    # if we meet a new character, put second into first, and reset second
            	else:
            		res = max(res, fc + sc) 
            		first, second, fc, sc, temp = second, c, temp, 1, 1         	   		
            res = max(res, fc + sc)
            return res
    

Log in to reply
 

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