LeetCode-Python [Longest Substring Without Repeating Characters]

题目:
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. 笨拙但易懂的方法

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:
            return 0
        MaxLen = 0 #需要返回的最大长度
        subStr = []
        subStr.append(list()) #add an list(), 每一组不重复的都存成一个list
        j = 0
        tmpLen = 0 #记录当前list的最大长度
        for num in s:
            if num not in subStr[j]: # 如果当前list里面没有该字母,加上该字母
                subStr[j].append(num) # add the character
                tmpLen = len(subStr[j])
            else:
                Index = subStr[j].index(num) # 查找当前num与第几个相同
                #print (Index)
                j = j+1 #已经与前面的有重复了,那么需要生成新的substring
                subStr.append(list()) #增加list()
                if (int(Index+1) == len(subStr[j-1])):#恰好等于最后一个数,也就是连着两个重复的
                    #print ("the same with the last one")
                    subStr[j].append(num)# 把最后那个加上

                if (subStr[j-1][Index+1:]):#如果不是等于最后一个数,那把从重复的那个数开始的后面一些数都加入到新的list中
                    for k in range(Index+1 , len(subStr[j-1])):
                        subStr[j].append(subStr[j-1][k])# 复制后面几个到新的list中
                    subStr[j].append(num)#以及append当前的num

            if (MaxLen < tmpLen):
                MaxLen = tmpLen

        return MaxLen

2. 简练代码

参考 https://github.com/illuz/leetcode

class Solution:  
    # @return an integer  
    def lengthOfLongestSubstring(self, s): 
    """
    :type s: str
    :rtype: int
    """ 
        res = 0  
        left = 0  
        d = {}  #创建字典,维护每个出现的字母的最大序号

        for i, ch in enumerate(s):  
            if ch in d and d[ch] >= left:  
                left = d[ch] + 1  
            d[ch] = i  #某个字母对应的最大的序号
            res = max(res, i - left + 1)  #(i-left+1)为到目前位置,本小节的长度
        return res  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值