3. 无重复字符的最长子串

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        n = len(s)]
        # 把s转为列表
        copy = list(s) # 空间复杂度O(n)  时间复杂度O(n)
        length = 0
        for left in range(n):
            window = []
            # left和right指针分别指向滑动窗口的两端
            # 先向右移动right,直到移动不了为止,比较并记下length
            # 然后移动left,生成新窗口,重新进行上述操作
            if copy[left] not in window:
                window.append(copy[left])
            right = left+1
            while right < n and copy[right] not in window:
                window.append(copy[right])
                right += 1
            if length < len(window):
                length = len(window)
        return length
            

官网答案更好一点

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
       

        window = set() # 用set更妙,这样不用每次在left循环的时候,都要使window=[]
        n = len(s)
        max_len = 0 
        right = 0
        for left in range(0, n):
            if left > 0:
                window.remove(s[left-1])
            # right = left  注意这个right应该在for left外面初始化
            # 每次遇到重复的数字,则只需要把left左移(并remove(s[left-1])),
            # 而right不变,因为下次循环还要继续判断right是否要加入window
            while right < n and s[right] not in window:
                window.add(s[right])
                right += 1
            if max_len < len(window):
                max_len = len(window)
        return max_len


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值