close
Question:
Given a string S, find the length of the longest substring T that contains at most two distinct characters.
For example,
Given S = “eceba”,
T is "ece" which its length is 3.
def question(s): hmap = {} left = 0 longest = 0 for right in xrange(len(s)): hmap[s[right]] = right if len(hmap) > 2: k = min(hmap, key=hmap.get) left = hmap[k] + 1 del hmap[k] longest = max(longest, right - left + 1) return longest if __name__ == '__main__': x = question('eceba') print x
全站熱搜