无重复字符的最长子串
2023-03-11 本文已影响0人
HellyCla
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
- 主要思想是滑窗并记录最大值
- 途径:使用字典记录出现的次数
- 踩坑注意:除了新创建key以外,还有以前有过这个字符,但是又去掉的情况,即dict_[s[ed]]==0。
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
st = 0
ed = 1
maxl = 1
if len(s) == 0:
return 0
if len(s) == 1:
return maxl
dict_ = {}
dict_[s[st]]=1
while ed < len(s):
if s[ed] not in dict_ or dict_[s[ed]]==0:
dict_[s[ed]]=1
ed+=1
continue
if dict_[s[ed]]>0:
dict_[s[ed]]+=1
maxl = max(maxl,ed-st)
while dict_[s[ed]]>1:
dict_[s[st]]-=1
st = st+1
ed = ed+1
maxl = max(maxl,ed-st)
return maxl