注意点:
- 空值的异常处理
- 滑动窗口的使用
- 利用字典(hash)来提高速度
源码如下:
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
s_dict = dict()
i, j = 0, 0
max_rec = 0
while j < len(s):
if s[j] in s_dict: #字典用于记录滑动窗口的左侧;
# 即发现重复字母后,快速将i放到上一个重复字母的右侧
i = max(s_dict[s[j]]+1, i)
s_dict[s[j]] = j
max_rec = max(max_rec, j - i + 1)
j += 1
return max_rec
网友评论