https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
解题思路
一遍扫描,碰到出现过的字符时:
1.更新更新当前不重复字符串的开始下标
2.如果不包括当前字符的不重复字符串到目前为止最长,更新rtv
代码
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
rtv = 0
seen = {}
start_idx = 0 # 当前无重复字符串的开始位置
for idx, c in enumerate(s):
if seen.get(c, -1) >= start_idx:
# 更新当前不重复字符串的开始下标
rtv = max(rtv, idx-start_idx)
start_idx = seen[c] + 1
seen[c] = idx
return max(rtv, len(s)-start_idx)