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
相关推荐
用户8356290780511 小时前
Python 实现 PDF 文件加密与解密方法
后端·python
用户8356290780511 小时前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
vibecoding日记3 小时前
双非如何快速入职字节等大厂大模型?真实案例分析:推理优化和投机解码
算法·求职·大模型工程师
yszaygr21385 小时前
Verilog参数化游程编码RLE模块
算法
望易5 小时前
刚设计的大模型架构-双域耦合认知框架
算法·架构
复杂网络9 小时前
多个 Claude Code 与多个 Codex 协同工作:设计与实现方案
算法
你好潘先生9 小时前
别再记命令了,用 yeero do 说句人话就能跑脚本,而且不烧 token
服务器·python·命令行
Agent_大师10 小时前
WebSocket 行情重连成功,K线缺口不会自动消失
python
荣码10 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
copyer_xyf10 小时前
FastAPI 如何连接 MySQL
后端·python