题解 | 连续子序列

连续子序列

https://www.nowcoder.com/practice/24b350b11af74d6782029fc9f7f0d5ef

import sys

line = sys.stdin.read().strip()

# 定义一个字典,键值对为{字符:位置}
dict = {}
# 定义滑动窗口的左右边界指针
i = j = 0
# answer, count
ans = count = 0

while j<len(line):
    # 当前字符不在滑动窗口中,执行的操作:加入,j自增,计数加一
    if line[j] not in dict:
        dict[line[j]] = j
        j += 1
        count += 1
    # 当前字符在滑动窗口中,执行的操作:记录计数,从字典中找到重复字符位置index,计算新的左指针i并删去新窗口之外的字符
    else:
        ans = max(ans, count)
        index = dict[line[j]]
        for n in range(i, index+1):
            del dict[line[n]]
            count -= 1
        i = index + 1

# 退出循环前可能产生了新的最大count
ans = max(count, ans)
print(ans)

全部评论

相关推荐

鲸鸿:实习协议不用管签多久,要走的时候提前三天说就可以了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务