This is a typical sliding window problem.
from collections import defaultdict
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
count = defaultdict(int)
lo = 0
hi = 0
max_length = 0
while hi < len(s):
new = s[hi]
count[new] += 1
hi += 1
while count[new] > 1:
count[s[lo]] -= 1
lo += 1
max_length = max(max_length, hi - lo)
return max_length