【每日一题Leetcode】LeetCode-3. Longest Substring Without Repeating Characters

给刷题日常换个窝  搬自https://zhuanlan.zhihu.com/p/36340355

今天的题目是给定一个字符串,返回无重复字符的最长子串
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.先判断是否空字符串

2.用两个指针计算长度

3.一个字典记录使用过的字符及索引位置,这样只需遍历一次

4.遍历s,当前位置字符出现在字典里,更新start为重复值的索引+1,即‘abcabc’中‘b’的索引值。end为当前索引值-1,即发生重复前最后一个字符的索引值。否则,start不变。end为当前索引值。

坑:当出现重复值的时候,需要增加一个判断条件,start值是否大于字典中记录的索引值。否则就会遇到下面的错误。

这里因为start是在遍历s时,出现重复字符时更新的。所以,需要增加一个判断条件,来对比新出现的重复字符的记录索引是否是start指针之前的位置。如果是,那么就不做更新。

最终提交Runtime: 84 ms
class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """     
        if len(s) == 0:
            return 0
        long = []#记录最长长度
        used = {}  #记录使用过的字母
        start = end = 0  #设定起始位置
        
        for idx,val in enumerate(s):         
            
            if val in used and start <= used[val]:
                start = used[val] + 1
                end = idx - 1
                
            else: 
                end = idx     
                
            used[val]=idx #更新字符索引
            long.append(end - start+1)
                         
        return max(long)



最终提交参考代码:https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1731/A-Python-solution-85ms-O(n)
如果使用参考代码的方法,long定义为0,更新max(long,(end-start+1)) 差不多速度,且不需要判断是否为空指符串。

 
 

猜你喜欢

转载自blog.csdn.net/github_39395521/article/details/80801495