LeetCode Longest Substring Without Repeating Characters 最长不重复子字符串问题(Python)

本文探讨了LeetCode中寻找最长不重复子字符串的问题,通过Python实现了一个只需遍历一次字符串的高效算法,避免了重复字符并利用哈希记录字母状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

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 subsequence and not a substring.

思路:

 看到这个“不重复”我基本就已经想着要用哈希了,初步思路是想将每个字符和位置对应成字典,如果出现重复字母,就重置字典,并将重复字母索引+1,开始新一轮索引。但这样遇到abcabcbb这种字符串的话,要循环太多遍,时间成本太高。后来想出来一种只需要循环一遍就可以的算法,重点是记录重复字母的标签,而不是清空字典,想明白这个之后就好写了。

代码如下:

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        d = {}
        start =long = 0
        for i in range(len(s)):
            #这里解释一下为什么要start<= d[s[i]],因为对于字符串tmmzuxt来说,当start指向第二个m,i已经到最后一个字母t的时候,这时候就不能将start重置为0+1,因为此时start已经在2了。
            if s[i] in d.keys() and start <= d[s[i]]:
                start = d[s[i]]+1
            else:
                long = max(long,i-start+1)
            d[s[i]]=i
        return long


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值