Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b59b9ba

Browse files
Initial commit
1 parent 96e3f30 commit b59b9ba

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Longest Substring with Same Letters after Replacement (hard)
2+
# Given a string with lowercase letters only, if you are allowed to replace no more than ‘k’ letters with any letter, find the length of the longest substring having the same letters after replacement.
3+
4+
# Input: String="aabccbb", k=2
5+
# Output: 5
6+
# Explanation: Replace the two 'c' with 'b' to have a longest repeating substring "bbbbb".
7+
8+
def length_of_longest_substring(str1, k):
9+
window_start, max_length, max_repeat_letter_count = 0, 0, 0
10+
frequency_map = {}
11+
12+
# Try to extend the range [window_start, window_end]
13+
for window_end in range(len(str1)):
14+
right_char = str1[window_end]
15+
if right_char not in frequency_map:
16+
frequency_map[right_char] = 0
17+
frequency_map[right_char] += 1
18+
max_repeat_letter_count = max(
19+
max_repeat_letter_count, frequency_map[right_char])
20+
21+
# Current window size is from window_start to window_end, overall we have a letter which is
22+
# repeating 'max_repeat_letter_count' times, this means we can have a window which has one letter
23+
# repeating 'max_repeat_letter_count' times and the remaining letters we should replace.
24+
# if the remaining letters are more than 'k', it is the time to shrink the window as we
25+
# are not allowed to replace more than 'k' letters
26+
if (window_end - window_start + 1 - max_repeat_letter_count) > k:
27+
left_char = str1[window_start]
28+
frequency_map[left_char] -= 1
29+
window_start += 1
30+
31+
max_length = max(max_length, window_end - window_start + 1)
32+
return max_length
33+
34+
35+
def main():
36+
print(length_of_longest_substring("aabccbb", 2))
37+
print(length_of_longest_substring("abbcb", 1))
38+
print(length_of_longest_substring("abccde", 1))
39+
40+
41+
main()

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /