Dummy python approach..


  • 0
    Q
    class Solution(object):
        def lengthOfLongestSubstringTwoDistinct(self, s):
            if s is None or len(s) == 0:
                return 0
            max_sub = 0
            first_right = 0
            second_right = 0
            cur_set = []
            left = 0
            for idx, char in enumerate(s):
                if len(cur_set) == 0:
                    first_right = idx
                    cur_set.append(char)
                elif char == cur_set[0]:
                    first_right = idx
                elif len(cur_set) == 1:
                    second_right = idx
                    cur_set.append(char)
                elif char == cur_set[1]:
                    second_right = idx
                else:
                    removed = min(first_right, second_right)
                    max_sub = max(max_sub, max(first_right, second_right) - left + 1)
                    left = removed + 1
                    if s[removed] == cur_set[0]:
                        first_right = idx
                        cur_set[0] = char
                    else:
                        second_right = idx
                        cur_set[1] = char
            return max(max_sub, max(first_right, second_right) - left + 1)
    

Log in to reply
 

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