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
相关推荐
星诺算法备案1 天前
读懂大模型备案流程,开启技术安全应用新征程
人工智能·算法·推荐算法·备案
Loo国昌1 天前
大型语言模型推理范式演进:从提示工程到思维算法
人工智能·算法·语言模型·自然语言处理
Dxy12393102161 天前
Python的正则表达式如何做数据校验
开发语言·python·正则表达式
Daily Mirror1 天前
Day38 MLP神经网络的训练
python
代码游侠1 天前
学习笔记——线程控制 - 互斥与同步
linux·运维·笔记·学习·算法
yaoh.wang1 天前
力扣(LeetCode) 66: 加一 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
聆风吟º1 天前
【数据结构手札】顺序表实战指南(一):线性表定义 | 顺序表定义
数据结构·顺序表·线性表
wanderist.1 天前
2025年蓝桥杯省赛C++大学A组
c++·算法·蓝桥杯
田姐姐tmner1 天前
Python 全面语法指南
开发语言·python
啊董dong1 天前
noi-2025年12月16号作业
数据结构·c++·算法·noi