Skip to content

Instantly share code, notes, and snippets.

@Bobronium
Created November 9, 2019 11:42
Show Gist options
  • Save Bobronium/4eb30be970e51330d2f1fe1425018d1e to your computer and use it in GitHub Desktop.
Save Bobronium/4eb30be970e51330d2f1fe1425018d1e to your computer and use it in GitHub Desktop.
import unittest
def find_longest_unique_substring(string: str) -> int:
"""
Returns length of the longest substring of unique characters
"""
max_length = 0
current_substr_chars = set()
start_index = leading_index = 0
str_length = len(string)
while start_index < str_length and leading_index < str_length:
char = string[leading_index]
if char not in current_substr_chars:
current_substr_chars.add(char)
leading_index += 1
current_length = len(string[start_index:leading_index])
max_length = max(max_length, current_length)
else:
# counting from a new start, so we need to exclude first seen char
# as it not a part of current substring anymore and can be repeated
current_substr_chars.remove(string[start_index])
start_index += 1
return max_length
class TestFundSubstring(unittest.TestCase):
in_out = {
'1234567AS9999999LLLLLL': 10, # 1234567AS9
'ABCDEEFGDKLMNOOO': 9, # EFGDKLMNO
'///AD1;AC;C;;C;C': 5, # /AD1;
'111111111111': 1, # 1
'111111222222': 2, # 12
'awesome': 6, # awesom
'ACDECOPGQAZM': 10, # DECOPGQAZM
'AAAAAAAAAAAA' * 10000: 1, # A
'': 0,
}
def test_find_longest_unique_substring(self):
for string, expected_length in self.in_out.items():
found_length = find_longest_unique_substring(string)
self.assertEqual(
expected_length,
found_length,
msg=f'Expected substring of {expected_length} unique chars, got {found_length} in {string}'
)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment