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

无重复字符的最长子串

Version 1

思路

  • 使用队列deque来实现滑动窗口

Code

python 复制代码
from collections import deque

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        

        if len(s) <= 1:
            return len(s)
            
        queue = deque()
        max_length = float('-inf')
        left = 0

        for right in range(len(s)): 
            cur_str = s[right]
            if cur_str not in queue:
                queue.append(cur_str)
            else:
                
                while cur_str in queue:     ### 收缩窗口
                    queue.popleft()
                    left += 1

                queue.append(cur_str)

            max_length = max(max_length, right - left + 1)  ## 计算没重复的最长字符串长度
         
        return max_length

Version 2

思路

  • 使用Set进行O(1)级别的查询以优化收缩窗口的判断实现

Code

python 复制代码
class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        

        if len(s) <= 1:
            return len(s)

### V2

        hash_set = set()
        max_length = float('-inf')
        left = 0

        for right in range(len(s)): 
            cur_str = s[right]
            if cur_str not in hash_set:
                hash_set.add(cur_str)
            else:
                
                while cur_str in hash_set:     ### 收缩窗口
                    pre_str = s[left]
                    hash_set.remove(pre_str)
                    left += 1                  ### 去掉重复的字母后向右移一位

                hash_set.add(cur_str)

            max_length = max(max_length, right - left + 1)  ## 计算没重复的最长字符串长度
         
        return max_length

Version 3

思路

  • 字符串本身也快速实现判断一个 子字符串 在 原字符串 中

Code

python 复制代码
class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        

        if len(s) <= 1:
            return len(s)


        max_str = ""
        max_length = float('-inf')
        left = 0

        for right in range(len(s)): 
            cur_str = s[right]
            if cur_str not in max_str:
                max_str += cur_str
            else:
                while cur_str in max_str:     ### 收缩窗口
                    max_str = max_str[1:]                ### 从左到右逐渐去掉字符
                    left += 1                  ### 去掉重复的字母后向右移一位

                max_str += cur_str

            max_length = max(max_length, right - left + 1)  ## 计算没重复的最长字符串长度
         
        return max_length
相关推荐
船厂电气自动化ai大模型29 分钟前
AI大模型与数学/第63课:矩阵定义、矩阵加法、标量乘法(逐级精讲)
数据结构·人工智能·深度学习·线性代数·算法
用户83562907805131 分钟前
使用 Python 管理 PDF 属性和元数据
后端·python
余额瞒着我当琳42 分钟前
算法修炼 chapter 2 双指针进阶、盛最多水的容器、有效三角形的个数、两数之和、三数之和、四数之和
算法
你压到我腿毛了66644 分钟前
C语言冒泡算法(Bubble sort)
c语言·数据结构·算法
猎嘤一号1 小时前
【2026 最新】Windows 11 右键菜单还原为 Windows 10 经典样式:一条命令、原理、回退与新版说明
windows·python
用户8356290780511 小时前
使用 Python 在 Word 文档中创建自定义图表
后端·python
靠沿2 小时前
贪心算法专题(三)
算法·贪心算法
super大力张2 小时前
MOE基于结构的药物设计(七):Ligand R-Vectors——如何判断配体可以从哪里继续生长?
数据库·算法·cadd·moe·svl·基于结构的药物设计
kyrie_sakura2 小时前
python学习笔记11 -- 进程和线程
笔记·python·学习