def lengthOfLongestSubstring(s): res = 0 d = {} tmp = 0 start = 0 for i in range(len(s)): if s[i] in d and d[s[i]] >= start: start = d[s[i]] + 1 tmp = i - start + 1 d[s[i]] = i res = max(res, tmp) return res print(lengthOfLongestSubstring("abcdbe")) # 4