Skip to content

Instantly share code, notes, and snippets.

@a-recknagel
Last active August 1, 2019 14:19
Show Gist options
  • Save a-recknagel/27cf47e085060b16e6449b467df13c9c to your computer and use it in GitHub Desktop.
Save a-recknagel/27cf47e085060b16e6449b467df13c9c to your computer and use it in GitHub Desktop.
find the longest subtring
def longest_substr(s):
"""Find the longest substring in a string.
This should be O(n), return value is the span
of the longest substring. In case there is
multiple longest substrings, the first one wins.
"""
start = end = 0
longest = (0, 0)
chars = set()
while True:
try:
next_ = s[end]
except IndexError:
return longest
if next_ in chars:
chars.remove(s[start])
start += 1
else:
chars.add(next_)
end += 1 # increment now already to get proper span indices
if (end-start) > (longest[1]-longest[0]):
longest = (start, end)
# >>> longest_substr('')
# (0, 0)
# >>> longest_substr('a')
# (0, 1)
# >>> longest_substr('aaaaaaaaaaaaaaaa')
# (0, 1)
# >>> longest_substr('aaaaaabaaaaaaaaa')
# (5, 7)
# >>> longest_substr('aaaaaabaaaabaaaa')
# (5, 7)
# >>> longest_substr('aaaaaabaaaabcaaa')
# (10, 13)
# >>> longest_substr('abcdefghijklmnop')
# (0, 16)
# >>> longest_substr('aaaaaaaaaaaaaaab')
# (15, 16)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment