-
Notifications
You must be signed in to change notification settings - Fork 891
/
problem_013.py
45 lines (37 loc) · 1.32 KB
/
problem_013.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
def get_longest_sub_with_k_dist(s, k):
if not s:
return ""
elif len(s) <= k:
return s
elif k == 1:
return s[0]
distinct_char_count = 0
seen_chars = set()
candidate = None
remaining_string = None
# to keep track of where the second character occurred
first_char = s[0]
second_char_index = 0
while s[second_char_index] == first_char:
second_char_index += 1
candidate = s
for index, char in enumerate(s):
if char not in seen_chars:
seen_chars.add(char)
distinct_char_count += 1
if distinct_char_count > k:
candidate = s[:index]
remaining_string = s[second_char_index:]
break
longest_remaining = get_longest_sub_with_k_dist(remaining_string, k)
longest_substring = None
if len(candidate) < len(longest_remaining):
longest_substring = longest_remaining
else:
longest_substring = candidate
return longest_substring
assert get_longest_sub_with_k_dist("abcba", 2) == "bcb"
assert get_longest_sub_with_k_dist("abccbba", 2) == "bccbb"
assert get_longest_sub_with_k_dist("abcbbbabbcbbadd", 2) == "bbbabb"
assert get_longest_sub_with_k_dist("abcbbbaaaaaaaaaabbcbbadd", 1) == "a"
assert get_longest_sub_with_k_dist("abccbba", 3) == "abccbba"