forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
longest-substring-with-at-most-k-distinct-characters.py
47 lines (42 loc) · 1.29 KB
/
longest-substring-with-at-most-k-distinct-characters.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# Time: O(n)
# Space: O(1)
class Solution(object):
def lengthOfLongestSubstringKDistinct(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
longest, start, distinct_count, visited = 0, 0, 0, [0 for _ in xrange(256)]
for i, char in enumerate(s):
if visited[ord(char)] == 0:
distinct_count += 1
visited[ord(char)] += 1
while distinct_count > k:
visited[ord(s[start])] -= 1
if visited[ord(s[start])] == 0:
distinct_count -= 1
start += 1
longest = max(longest, i - start + 1)
return longest
# Time: O(n)
# Space: O(1)
from collections import Counter
class Solution2(object):
def lengthOfLongestSubstringKDistinct(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
counter = Counter()
left, max_length = 0, 0
for right, char in enumerate(s):
counter[char] += 1
while len(counter) > k:
counter[s[left]] -= 1
if counter[s[left]] == 0:
del counter[s[left]]
left += 1
max_length = max(max_length, right-left+1)
return max_length