给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串的长度。

暴力搜索的方法并不难,复杂度为O(N^2)

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        n = len(s)
        result=0
        for i in range(n):
            a_set=()
            temp=0
            for j in range(i,n):
                if s[j] not in a_set:
                    a_set.add(s[j)
                    temp+=1
                else:
                    break
            result = max(result,temp)
        return result

假如有个字符串是a b c d e f g h e m n p,在上面的解法中先从第a开始找一下最大的无重复字符串a->h,再从b开始找最大无重复字符串b->h。其实,从b c d e这些查找都是无用的,因为重复字符串是e,从b c d e开始的最大不重复字符串不会长于从a开始的不重复字符串。

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        n = len(s)
        result = 0 
        fast,slow = 0,0

        a_set = set()
        while fast<n:
            if s[fast] not in a_set:
                a_set.add(s[fast])
                result = max(result,fast-slow+1)
                fast+=1
            else:
                a_set.remove(s[slow])                
                slow += 1
        return result