题目
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
输入: “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
思路
尺取法
代码
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
dic={}
l=r=0
ans=0
res=0
while r < len(s):
while r<len(s) and (s[r] not in dic or dic[s[r]]==0):
dic[s[r]]=1
r+=1
res=r-l
ans=max(res,ans)
#print(r,l,ans)
if r==len(s):
return ans
while l<r:
if s[l]==s[r]:
dic[s[l]]=1
l+=1
break
else:
dic[s[l]]=0
l+=1
res=r-l+1
ans=max(res,ans)
r+=1
return ans