Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nhudinhtuan/aec549e94bf3ef25f68b1d126e1091d2 to your computer and use it in GitHub Desktop.
Save nhudinhtuan/aec549e94bf3ef25f68b1d126e1091d2 to your computer and use it in GitHub Desktop.
length of longest unique substring
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