給定一個字符串 s ,請你找出其中不含有重復字符的 最長子串 的長度。
- 主要思想是滑窗并記錄最大值
- 途徑:使用字典記錄出現(xiàn)的次數(shù)
- 踩坑注意:除了新創(chuàng)建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