Description
Given a string, find the length of the longest substring without repeating characters.
Solution
循环一遍,每次对当前位置之前的每个字母从后往前第二次出现的位置取max,与当前位置做差,即得到答案,用字典实现复杂度为O(n)
Code
class Solution(object):
def lengthOfLongestSubstring(self, s):
n=len(s)
ex={}
pos=-1
res=0
for i in range(n):
pos=max(pos,ex.get(s[i],-1))
ex[s[i]]=i
res=max(res,i-pos)
return res