3. Longest Substring Without Repeating Characters

3Longest Substring Without Repeating Characters

题目描述

 

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

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring"pwke" is a subsequenceand not a substring.

分析

只需要返回最大长度值,所以只需要一个int型变量保存返回结果;

定义两个指针,记录当前找到的无重复子串的起始和终止位置(终止即当前遍历到的索引位置)。

完整代码

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        maxlen=start=0
        used={}        #保存已遍历的字符和最近出现的位置
        for i,c in enumerate(s):
            if c in used and start<=used[c]:    #若当前字符之前出现过,并且在start之后
                start=used[c]+1     #更新起点
            else:   
                maxlen=max(maxlen,i-start+1)    #更新最大长度
            used[c]=i   #更新字符出现的位置
        return maxlen

第二次做:出错:“dvdf”的答案为2

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        d = {}
        fir = sec = 0
        ans = 0
        le = len(s)
        while fir<le:
            if sec < le:
                c = s[sec]
                if c in d and fir<=d[c]:
                    fir = d[c] + 1
                d[c] = sec
                ans = max(sec - fir+1, ans)
                sec = sec + 1
            # 当到达右边界但未到达左边界时,左边界右移继续循环
            else:
                sec = fir = fir+1
            
        return ans

tips:

1. 当右指针到达右边界时,左指针需要右移,直到左右都到达右边界为止。

2. 更新左指针时,必须以重复元素之前的位置开始右移,而不是以最初的左指针位置开始右移。

出错:if c in d and fir<=d[c]:

必须保证fir是在原始d[c]的右边,才可以将fir更新为d[c]+1,否则,只需要更新d[c]的值即可。

需要先在滑动窗口内去掉这个已经出现过的字符了,去掉的方法并不需要将左边界left一位一位向右遍历查找,由于我们的HashMap已经保存了该重复字符最后出现的位置,所以直接移动left指针就可以了。

3. 判断是否存在问题,使用hashmap,因为hash的速度最快。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值