Skip to content

Instantly share code, notes, and snippets.

@abrarShariar
Last active November 8, 2020 12:08
Show Gist options
  • Save abrarShariar/1bad9c43191d696fa72d51c7272ee57e to your computer and use it in GitHub Desktop.
Save abrarShariar/1bad9c43191d696fa72d51c7272ee57e to your computer and use it in GitHub Desktop.
longest substring code
def length_of_longest_substring(str1, k):
window_start, max_length, max_repeat_letter_count = 0, 0, 0
frequency_map = {}
# Try to extend the range [window_start, window_end]
for window_end in range(len(str1)):
right_char = str1[window_end]
if right_char not in frequency_map:
frequency_map[right_char] = 0
frequency_map[right_char] += 1
max_repeat_letter_count = max(
max_repeat_letter_count, frequency_map[right_char])
# Current window size is from window_start to window_end, overall we have a letter which is
# repeating 'max_repeat_letter_count' times, this means we can have a window which has one letter
# repeating 'max_repeat_letter_count' times and the remaining letters we should replace.
# if the remaining letters are more than 'k', it is the time to shrink the window as we
# are not allowed to replace more than 'k' letters
current_length = window_end - window_start + 1
if (current_length - max_repeat_letter_count) > k:
left_char = str1[window_start]
frequency_map[left_char] -= 1
window_start += 1
max_length = max(max_length, current_length)
return max_length
def main():
print(length_of_longest_substring("aabccbb", 2))
print(length_of_longest_substring("abbcb", 1))
print(length_of_longest_substring("abccde", 1))
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment