3. Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", which the length is 3.
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3. 
             Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

这道题乍看还是比较简单,但是有很多细节在里面,先给一下实现代码

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        maxlen = 0
        start = 0
        dt = {}
        for i,c in enumerate(s):
            if c in dt:
                start = max(start,dt[c]+1)
            maxlen = max(maxlen,i-start+1)   
            dt[c] = i
        return maxlen 

首先关键就在于:

start = max(start,dt[c]+1)

笔者之前是:

start = dt[c]+1

对比两者的差别,错误样本是:

abba

0,1,2,3

当判断第二个a时,start此时就在2的位置,如果采用笔者之前的,那么start其实在1,但是bb也就是中间已经重复了,换句话说:

......a....c.............c.....a............b................

......a....c.............c.....a............b................

当我们在第二个a的位置时候,原本来说是两个a的之间的长度,但有可能其中间有部分已经重复,例如红色的部分,所以这样做是错的,当使用了

start = max(start,dt[c]+1)

此时start应该在第一个C的下一个位置,所以

i-start后应该是绿色部分,符合我们想要的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值