原题目:力扣
给定一个字符串 s
,请你找出其中不含有重复字符的 最长子串 的长度。
def lengthOfLongestSubstring(s):
# 第一步,处理特殊情况
if s=='':
return 0
begin,end=0,0
cur=1 #当前正在遍历哪个字符
res=1
while cur<len(s):
#如果当前字符不在我们所选定的范围内
if s[cur] not in s[begin:end+1]:
end=cur
#如果当前字符在选定的范围内,就要让begin回退到在选定范围内s[cur]出现的位置后面
else:
res=max(res,end-begin+1)
begin=s.index(s[cur],begin,end+1)+1
end=cur
cur+=1
res=max(res,end-begin+1)
return res
思想和动态规划比较像,即需要考虑当前字符如果在范围内如何处理,如果不在,那如何处理,最终就能得到结果