classSolution:deflengthOfLongestSubstring(self,s:str) ->int: mydict = collections.defaultdict(int) l =0 res =0for r, char inenumerate(s): mydict[char]+=1while mydict[char]>1: mydict[s[l]]-=1 l +=1 res =max(res, r - l +1)return res
时间复杂度:O(n)
空间复杂度:O(1)
双指针/记录位置
classSolution:deflengthOfLongestSubstring(self,s:str) ->int: mydict ={} start =0 res =0for i, char inenumerate(s):if char notin mydict: dist = i - start +1 res =max(res, dist)else:if mydict[char]>= start: start = mydict[char]+1else: res =max(res, i - start +1) mydict[char]= ireturn res
classSolution(object):deflengthOfLongestSubstring(self,s): left =0 res =0for right, char inenumerate(s): pos = s.find(char, left, right)# 维护一个dict来储存pos而不是每次都使用find来找if pos >=0: left = pos +1if right - left +1> res: res = right - left +1return res