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

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 g0d2 的頭像
    g0d2

    kazi1@的部落格

    g0d2 發表在 痞客邦 留言(0) 人氣()