leetcode题目3---Longest Substring Without Repeating Characters

题目描述:

Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: 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.

第一回:

思路:依次遍历,存在字典中,当有重复的出现,进行长度更新,字典重置。新的位置更新到重复出现的位置。

class Solution(object):

    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:
            return 0
        length = maxLength = 1
        strDic = {}
        i = 0
        lenS = len(s)
        while(lenS):
            strDic[s[i]] = i
            try:
                strDic[s[i + 1]] #判断下一个在字典中是否出现,既重复。
                i = strDic[s[i + 1]]/#若出现,新的遍历位置为此重复的字符位置
                maxLength = max(maxLength, length)
                strDic = {}
                length = 1
            except KeyError:#字典中不出现,会有KeyError错误。长度增加。
                length += 1
            except IndexError:
                return max(maxLength, length)
            i += 1
        return maxLength

发现此方法的复杂度,最坏时刻,也是O(N*N)

第二回:

想着,在重复位置逻辑处,进行优化,遍历过程中,将最大的重复位置记录下来,遍历中当有新的重复位置时,更新最大重复位置。更新重复位置值。代码如下:

应用桶存放机制。将字符转换为ACSII值,作为下标,其值为此字符在原始s中的位置。

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:
            return 0
        maxLength = 1
        strList = [-1] * 300  #长度为300的,值为-1的列表(桶)
        maxRepetitionIndex = -1
        for i in range(0, len(s)):
            if strList[ord(s[i])] > maxRepetitionIndex: #此处比较新的重复位置和最大重复位置
                maxRepetitionIndex = strList[ord(s[i])]
            strList[ord(s[i])] = i #列表更新
            maxLength = max(maxLength, i - maxRepetitionIndex)
        return maxLength

复杂度为O(N),但是需要开辟一定长度的list,(长度为字符ACSII的范围,大于也可以。)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值