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: tis “ece” which its length is 3.
Example 2:
Input: “ccaabbb”
Output: 5
Explanation: tis “aabbb” which its length is 5.
def longestsubstring(s):
l=0
j=0
dic={}
for j in range(len(s)):
dic[s[j]]=dic.get(s[j],0)+1
while len(dic.keys())>2:
dic[s[l]]-=1
if dic[s[l]]==0:
dic.remove(s[l])
l+=1
ret=max(ret,j-l+1)
return ret
huntershuai
发布了68 篇原创文章 · 获赞 9 · 访问量 2万+
私信
关注