I had the same idea with yours,

Here is my code.

class Solution:
# @return an integer
def lengthOfLongestSubstring(self, s):
hash,maxLen,lastIdx={},0,0;
for i in range(len(s)):
if(s[i] in hash):
if(hash[s[i]]>=lastIdx):
maxLen=max(maxLen,i-hash[s[i]]); # the range between same char.
maxLen=max(maxLen,i-lastIdx); # the range before the second char.
lastIdx=hash[s[i]]+1
hash[s[i]]=i;
# reach the edge of array.
maxLen=max(maxLen,len(s)-lastIdx)
return maxLen;