-
Notifications
You must be signed in to change notification settings - Fork 3
/
l332.py
31 lines (31 loc) · 850 Bytes
/
l332.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution(object):
def lengthOfLongestSubstringKDistinct(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
i, j, d, cnt, res, l = 0, 0, {}, 0, 0, len(s)
while j < l:
while j < l:
e = s[j]
if d.get(e) is None:
d[e] = 1
cnt += 1
if cnt > k:
break
else:
d[e] += 1
j += 1
res = max(res, j-i)
j += 1
while cnt > k:
if i > j:
return 'error i > j'
e = s[i]
d[e] -= 1
if d[e] == 0:
del d[e]
cnt -= 1
i += 1
return res