Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Longest unique substring -- using for loops solution in Clear category for Longest Substring of Unique Characters by MarHar
def longest_substr(s: str) -> int:
'''
Given a string s, determine its longest substring of unique characters.
Return length of longest substring.
'''
# substring holder
sub = ''
# longest substing
long = ''
# start at each index in the string
for i in range(len(s)):
# go through the following characters by index
# i+j ranges from i to the index of the last char
for j in range(len(s) - i):
# if char isn't in current substring being built, add it.
if s[i+j] not in sub:
sub += s[i+j]
# non unique char:
else:
# if this substring is the longest one found so far, use it to replace longest.
long = sub if len(sub) > len(long) else long
sub = '' # clear current substring
break # quit looking once nonunique char found
# for debugging
print(f'longest unique substring in {s}:\t{long}\t({len(long)})\n')
# return length of longset substring
return len(long)
print("Example:")
print(longest_substr("abcabcbb"))
# These "asserts" are used for self-checking
assert longest_substr("abcabcbb") == 3
assert longest_substr("bbbbb") == 1
assert longest_substr("pwwkew") == 3
assert longest_substr("abcdef") == 6
assert longest_substr("") == 0
assert longest_substr("au") == 2
assert longest_substr("dvdf") == 3
print("The mission is done! Click 'Check Solution' to earn rewards!")
Oct. 26, 2023
Comments: