Skip to content

Commit 376fedc

Browse files
committed
add another solution
1 parent 614cf36 commit 376fedc

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

Python/longest-substring-with-at-most-k-distinct-characters.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,27 @@ def lengthOfLongestSubstringKDistinct(self, s, k):
2323
longest = max(longest, i - start + 1)
2424
return longest
2525

26+
27+
# Time: O(n)
28+
# Space: O(1)
29+
from collections import Counter
30+
31+
32+
class Solution2(object):
33+
def lengthOfLongestSubstringKDistinct(self, s, k):
34+
"""
35+
:type s: str
36+
:type k: int
37+
:rtype: int
38+
"""
39+
counter = Counter()
40+
left, max_length = 0, 0
41+
for right, char in enumerate(s):
42+
counter[char] += 1
43+
while len(counter) > k:
44+
counter[s[left]] -= 1
45+
if counter[s[left]] == 0:
46+
del counter[s[left]]
47+
left += 1
48+
max_length = max(max_length, right-left+1)
49+
return max_length

0 commit comments

Comments
 (0)