Created
September 15, 2019 17:50
-
-
Save santhalakshminarayana/10b8506e93ed01b4c8b23abf24d876cb to your computer and use it in GitHub Desktop.
Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "bcb". | |
''' | |
def long_substr(s,k): | |
long_st=0 | |
has_found=0 | |
dq=[] | |
mapp=dict() | |
for i,ch in enumerate(s): | |
if(mapp.get(ch,-1) is -1): | |
mapp[ch]=1 | |
dq.append(i) | |
else: | |
mapp[ch]+=1 | |
dq.append(i) | |
if(len(mapp)>k): | |
mapp[s[dq[0]]]-=1 | |
if(mapp[s[dq[0]]]==0): | |
del mapp[s[dq[0]]] | |
dq.pop(0) | |
if(len(mapp)==k): | |
long_st=max(long_st,dq[-1]-dq[0]+1) | |
if long_st==0: | |
return -1 | |
else: | |
return long_st |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment