Created
December 25, 2020 06:02
-
-
Save codecakes/32060bef4dc321258b87dce80e1fb5f3 to your computer and use it in GitHub Desktop.
Longest substring without any repeating characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def non_repeat_substring(string): | |
from collections import Counter | |
max_ctr = Counter() | |
left_idx = 0 | |
distinct = 0 | |
max_distinct = float('-inf') | |
for right_idx, r_char in enumerate(string): | |
if not max_ctr[r_char]: | |
distinct += 1 | |
max_ctr[r_char] += 1 | |
while max_ctr[r_char] > 1: | |
l_char = string[left_idx] | |
max_ctr[l_char] -= 1 | |
if not max_ctr[l_char]: | |
distinct -= 1 | |
left_idx += 1 | |
max_distinct = max(max_distinct, distinct) | |
return max_distinct |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment