longest-substring.py (768B)
1 class Solution: 2 def lengthOfLongestSubstring(self, s: str) -> int: 3 4 left_ptr = 0 5 right_ptr = 0 6 longest = 0 7 hash_map = {} 8 9 while right_ptr < len(s): 10 11 # if the right side is in the map, remove characters until it is no longer there 12 if s[right_ptr] in hash_map: 13 while s[right_ptr] in hash_map: 14 del hash_map[s[left_ptr]] 15 left_ptr += 1 16 hash_map[s[right_ptr]] = right_ptr 17 else: 18 hash_map[s[right_ptr]] = right_ptr 19 current_len = (right_ptr - left_ptr) + 1 20 if current_len > longest: 21 longest = current_len 22 23 right_ptr += 1 24 25 return longest