Created
March 30, 2020 06:49
-
-
Save nhudinhtuan/aec549e94bf3ef25f68b1d126e1091d2 to your computer and use it in GitHub Desktop.
length of longest unique substring
This file contains 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 longest_unique_substring(s): | |
# function to check if the characters in the substring are all unique or not | |
def is_all_unique(start_index, end_index): | |
character_set = set() | |
for z in range(start_index, end_index): | |
if s[z] in character_set: | |
return False | |
character_set.add(s[z]) | |
return True | |
longest_length = float('-inf') | |
n = len(s) | |
# empty string has 0 substring | |
if n == 0: | |
return 0 | |
# enumerate all substrings [i, j) | |
for i in range(n): | |
for j in range(i + 1, n + 1): | |
# if the characters in the substring are all unique, compare the length. | |
if is_all_unique(i, j): | |
longest_length = max(longest_length, j - i) | |
return longest_length |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment