双指针解法 通过所有算例,耗时短,供参考 def lengthOfLongestSubstring(self , s: str) -> int: cnt = 1 i = 0 k = 1 while i < len(s)-1 and k < len(s): if s[k] not in s[i: k]: cnt = max(cnt, len(s[i: k+1])) k += 1 elif s[k] in s[i: k]: i += 1 k = i+1 return cnt