leecode 无重复字符的最长子串的三种解决方法

leecode 无重复字符的最长子串

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

示例 1:

输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:

输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:

输入: “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
方法一:利用字典当中的键值不能重复的特点,当出现字典的长度小于循环的次数时,一定有重复的字符出现,此时记录字符长度。在将字符串去掉最左边的字符,开始下一次查询。

class Solution:
    def lengthOfLongestSubstring(self, s):

        lenth=1
        lenth_max=0
        while len(s)!=0:
            dict1={}
            lenth = 1
            for num1,letter in enumerate(s):
                dict1[letter]=num1
                if len(dict1)<lenth:
                    break
                lenth+=1
            if lenth_max<lenth-1:
                lenth_max=lenth-1
            s=s[1:]
        print(lenth_max)
        return lenth_max

但是这种方法不太好,有些拐弯抹角,不直接

方法二:滑动窗口的经典方法

class Solution:
    def lengthOfLongestSubstring(self, s):
        window=[]
        lenth_max=0
        for n in s:
            if n not in window:
                window.append(n)
            else:
                window.append(n)
                window=window[window.index(n)+1:]
            lenth_max=max(len(window),lenth_max)
        print(lenth_max)
        return lenth_max

效果还行
在这里插入图片描述

但是我们发现还有改进的空间,在查找字符是否在字符串的过程中,我们可以利用字典(哈希表)来实现快速查找,从而加快速度

方法三:在二的基础上稍作改进,使用字典来提高查找效率:

class Solution:
    def lengthOfLongestSubstring(self, s):

        dict1={}
        lenth_max=0
        i=-1
        for n,letter in enumerate(s):
            if letter in dict1 and dict1[letter] > i:
                i=dict1[letter]
                dict1[letter] = n
            else:
                dict1[letter] = n
                lenth_max=max(n-i,lenth_max)
        print(lenth_max)
        return(lenth_max)

效果不错
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值