A simple Python solution


  • 0
    I

    Here is a simple python solution. just use a
    defaultdict as counter for substring s[i, j]

    '''
    class Solution(object):
    def lengthOfLongestSubstringTwoDistinct(self, s):
    """
    :type s: str
    :rtype: int
    """
    maxlen = 0
    i = 0
    d = collections.defaultdict(int)
    for j, c in enumerate(s, 1):
    d[c] += 1
    while (len(d)) > 2:
    c = s[i]
    d[c] -= 1
    if d[c] == 0:
    del d[c]
    i += 1
    maxlen = max(maxlen, j-i)
    return maxlen
    '''


Log in to reply
 

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