第3题:最长无重复字符子串(Python版本)
发布时间
阅读量:
阅读量
def run(s):
"""
:type s: str
:rtype: int
"""
n = len(s)
# 创建集合, 记录每个字符是否出现过
sett = set()
# 设置右指针初始值为-1,相当于在字符串的左边界的左侧,还没有开始移动
right = -1
# res记录无重复字符串的最长长度
res = 0
for left in range(n):
# 左指针向右移动一格
if left != 0:
# 移除最左边的字符
sett.remove(s[left - 1])
while right + 1 < n and s[right + 1] not in sett:
# 若该字符以前在未集合sett中出现过,则不断向右移动右指针
sett.add(s[right + 1])
right += 1
# 通过原有字符最大长度res与现有最大字符长度right-left+1比较,得到最长字符串的长度
res = max(res, right - left +
全部评论 (0)
还没有任何评论哟~
