leetcode 3. Longest Substring Without Repeating Characters 最长非重复子串的长度 滑动窗口法

这里写图片描述
题目链接

根据我们之前介绍的滑动窗口法的解法:
滑动窗口法详解
leetcode 438. Find All Anagrams in a String 滑动窗口法
这题,我们不难解决,使用之前的模板。可得如下解法

from collections import defaultdict

class Solution:
    def lengthOfLongestSubstring(self, s):
        begin, end , counter, d = 0, 0, 0, 0
        map_dict = defaultdict(int)
        while end < len(s):
            c = s[end]
            map_dict[c] += 1
            # counter表示重复字符的个数
            if map_dict[c] > 1:
                counter += 1
            end += 1
            # 将begin一直移到第一个重复字符的位置
            while counter > 0:
                char_tmp = s[begin]
                if map_dict[char_tmp] > 1:
                    counter -= 1
                map_dict[char_tmp] -= 1
                begin += 1
            # 每次计算下当前子串长度
            d = max(d, end - begin)
        return d

提供一种更短的解法:

class Solution:
    def lengthOfLongestSubstring(self, s):
        dic, res, start, = {}, 0, 0
        for i, ch in enumerate(s):
            if ch in dic:
                start = max(start, dic[ch]+1)
            res = max(res, i-start+1)
            dic[ch] = i
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值