159. Longest Substring with At Most Two Distinct Characters

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.

Solution

(1) Java



(2) Python

class Solution:
    def lengthOfLongestSubstringTwoDistinct(self, s):
        """
        :type s: str
        :rtype: int
        """
        rst = 0
        wd = {}
        i = 0
        for j, v in enumerate(s):
            if not v in wd:
                wd[v] = 1
            else:
                wd[v] = wd[v]+1
            if len(wd) > 2:
                rst = max(rst, j-i)
            else:
                rst = max(rst, j-i+1);
            while len(wd) > 2:
                c = s[i]
                wd[c] = wd[c]-1
                if wd[c] == 0:
                    del wd[c]
                i += 1
        return rst

(3) Scala



results matching ""

    No results matching ""