[LeetCode] 3. Longest Substring Without Repeating Characters(Python)

本文介绍了LeetCode中的一道经典问题——求最长无重复字符子串,给出了两种Python实现思路。第一种通过字符表判断,第二种使用字典记录字符位置并更新最长子串。代码简洁高效,适用于字符串处理和算法学习。
摘要由CSDN通过智能技术生成

[LeetCode] 3. Longest Substring Without Repeating Characters(Python)

1. 题目

Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example 2:
Input: s = “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example 3:
Input: s = “pwwkew”
Output: 3
Explanation: The answer is “wke”, with the length of 3. Notice that the answer must be a substring, “pwke” is a subsequence and not a substring.
Example 4:
Input: s = “”
Output: 0
Constraints:
0 <= s.length <= 5 * 104
s consists of English letters, digits, symbols and spaces.

2. 题目理解

输入一个字符串,输出该字符串中最长不重复子串的字符数。

3. 代码实现

1)思路一
将本位存到字符表中,判断下一位字符是否存在于字符表相同:若不同,temp+1,并加入字符表;若相同,temp_max为当前最长字符数,清空字符表,并从下一位开始判断。但存入字符表再进行字符表的匹配会造成一些冗余。
2)思路二
构建字典dict,起始位start,长度最大值maxl。若字典中存在当位且字典中存储的值+1大于起始位的值,起始位改为当前位+1。将当前位更新到字典中,并将当前最长不重复字符数maxl更新为当前位-start+1与当前maxl中的较大值。

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        start = 0
        maxl = 0
        dict = {}
        for i, value in enumerate(s):
            if s[i] in dict and dict[value]+1 > start:
                start = dict[value] + 1
            dict[value] = i
            maxl = max(i-start+1, maxl)
        return maxl
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值