Created
March 30, 2020 08:55
-
-
Save nhudinhtuan/0ef426fa1e854632a0c208d2b151cc38 to your computer and use it in GitHub Desktop.
length of longest unique substring
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
from collections import defaultdict | |
def longest_unique_substring(s): | |
longest_length = float('-inf') | |
n = len(s) | |
# empty string has the longest length is 0 | |
if n == 0: | |
return 0 | |
left = 0 | |
right = 0 | |
window = defaultdict(int) | |
while right < n: | |
# sliding the window to the right | |
right_character = s[right] | |
window[right_character] += 1 | |
right += 1 | |
# if a duplicate character appears in the window | |
# drop off the left elements until we have valid condition again | |
while window[right_character] > 1: | |
window[s[left]] -= 1 | |
left += 1 | |
longest_length = max(longest_length, right - left) | |
return longest_length |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment