class Solution:
# @return an integer
def lengthOfLongestSubstring(self, s):
start = maxLength = 0
usedChar = {}
for i in range(len(s)):
if s[i] in usedChar and start <= usedChar[s[i]]:
start = usedChar[s[i]] + 1
else:
maxLength = max(maxLength, i  start + 1)
usedChar[s[i]] = i
return maxLength
A Python solution  85ms  O(n)


"Graceful indeed,but it stiill can be optimised by check wether the remaining string length [start ~ ] are shorter then current max length. if it's, return."
I thought so too at the beginning. But turns out the maxLength can still grow if the remaining string contains chars that are not in the current maxLength string. So return at this point will result in smaller values than the truth.


How about accessing the index of duplicate letter when necessary?
max_length = 0 longest_substring = '' for letter in s: if letter not in longest_substring: longest_substring += letter else: longest_substring = longest_substring[longest_substring.index(letter)+1:] + letter # access the index of duplicate letter in the substring and leave the right side and plus the new letter if len(longest_substring) > max_length: max_length = len(longest_substring) return max_length