思路:滑动窗口,通过check函数来判断是否数组元素唯一,若不唯一,更新start位置,若唯一,更新max_len

Python:

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        max_len=float('-inf')
        def check(adict):
            for key in adict:
                if adict[key]>1:
                    return False
            return True
        start=0
        adict={}
        for end in range(len(s)):
            if s[end] not in adict:
                adict[s[end]]=1
            else:
                adict[s[end]]+=1
            while not check(adict):
                adict[s[start]]-=1
                if adict[s[start]]==0:
                    del adict[s[start]]
                start+=1
            max_len=max(end-start+1,max_len)
        if max_len==float('-inf'):
            return 0
        else:
            return max_len