其他分享
首页 > 其他分享> > [LeetCode] 159. Longest Substring with At Most Two Distinct Characters

[LeetCode] 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: 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万+ 私信 关注

标签:159,Explanation,Two,ret,dic,Substring,length,Input,tis
来源: https://blog.csdn.net/huntershuai/article/details/104171532