Longest Substring with atmost two distinct characters
Problem Link 1: https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/
Problem Link 2: https://www.lintcode.com/problem/longest-substring-with-at-most-two-distinct-characters/description
class Solution:
"""
@param s: a string
@return: the length of the longest substring T that contains at most 2 distinct characters
"""
def length_of_longest_substring_two_distinct(self, s: str) -> int:
# Write your code here
d={}
j=0
ans=0
n=len(s)
for i in range(n):
if(s[i] in d):
d[s[i]]+=1
else:
d[s[i]]=1
while(len(d)>2):
if(d[s[j]]==1):
del d[s[j]]
j+=1
else:
d[s[j]]-=1
j+=1
ans=max(ans,i-j+1)
return ans
Last updated