LeetCode第三题:无重复字符的最长子串python解法

在这里插入图片描述
英文题介绍:
在这里插入图片描述

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        temp = ''
        length = 0
        for i in s:
            if i not in temp:
                temp+=i
                length = max(length,len(temp))
            else:
                temp+=i
                temp = temp[temp.index(i)+1:]
        return length

在这里插入图片描述

知识点:

1.本题所需知识点:
在这里插入图片描述
链接:http://www.runoob.com/python/python-strings.html
求字符串的下标,或叫索引。
2.我一开始犯的错:
错误代码>>>

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        temp = ''
        length = 0
        for i in s:
            if i not in temp:
                temp+=i
                #length = max(length,len(temp))
            else:
       			length = max(length,len(temp))
                temp+=i
                temp = temp[temp.index(i)+1:]
        return length

这样会通过大部分实例,但是无法通过。一开始没有注意,后来发现犯的错误很简单:
当字符串为单个字符或者全是不重复的时候,根本不会进else循环中。
就是对于每个i,都只在if里就结束,else形同虚设,所以length就一直为0。
3.代码讲解
代码很简单,重点说一下两句代码:
首先,temp是存储遍历过的字符的。length是存储遇到的子字符串的最长长度的。

 temp = temp[temp.index(i)+1:]

当遇到重复的时候,应该把重复的第一个去除,从后面一个开始算了。即:
子串为abc了,这时候再来一个a,那么新的字串应该是bca了。也就是把原字串的第一个a去掉,从b开始计,用时把新的a加上。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值