longest_substring.py 887 B

123456789101112131415161718192021222324252627282930
  1. # Given a string, find the length of the longest substring without repeating characters.
  2. # Time complexity: worst O(n^2), best O(n). Using hash table to check unique
  3. # reduces to always O(n^2)
  4. # Space complexity: O(n/2)
  5. import pytest
  6. def test_longest_substring():
  7. cases = ['a', 'aaaa','pwdkee', 'asdfghjkl']
  8. expected = [1, 1, 5, 9]
  9. for c,e in zip(cases,expected):
  10. assert longest_substring(c) == e
  11. def longest_substring(s):
  12. len_s = len(s)
  13. if len_s <= 1:
  14. return len_s
  15. len_longest = 0
  16. sub_str = []
  17. for i in range(len_s):
  18. for j in range(i,len_s):
  19. if s[j] not in sub_str:
  20. sub_str.append(s[j])
  21. else:
  22. i = j
  23. if len(sub_str) > len_longest:
  24. len_longest = len(sub_str)
  25. sub_str = []
  26. break
  27. return len_longest