Leetcode 159. 至多包含两个不同字符的最长子串

1.题目基本信息

1.1.题目描述

给你一个字符串 s ,请你找出 至多 包含 两个不同字符 的最长子串,并返回该子串的长度。

1.2.题目地址

https://leetcode.cn/problems/longest-substring-with-at-most-two-distinct-characters/description/

2.解题方法

2.1.解题思路

滑动窗口

2.2.解题步骤

第一步,定义维护变量。left和right为滑动窗口的左右指针;map_记录子串中单字符最右端的索引位置

第二步,滑动窗口进行滑动,更新maxLength

  • 2.1.删除map_中最左边的字符映射

  • 2.2.重置left指针

  • 2.3.更新maxLength

3.解题代码

python代码

python 复制代码
class Solution:
    def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
        if len(s)<=2:
            return len(s)
        length=len(s)
        # 第一步,定义维护变量。left和right为滑动窗口的左右指针;map_记录子串中单字符最右端的索引位置
        left,right=0,0
        map_={}
        # 第二步,滑动窗口进行滑动,更新maxLength
        maxLength=2
        for i in range(length):
            char = s[i]
            right = i
            map_[char] = right
            # 2.1.删除map_中最左边的字符映射
            if len(map_)>=3:
                minValue=min(map_.values())
                for key,value in map_.copy().items():
                    if value==minValue:
                        del(map_[key])
                # 2.2.重置left指针
                left=minValue+1
            # 2.3.更新maxLength
            maxLength=max(maxLength,right-left+1)
        return maxLength

4.执行结果

相关推荐
flashlight_hi25 分钟前
LeetCode 分类刷题:74. 搜索二维矩阵
python·算法·leetcode·矩阵
小年糕是糕手29 分钟前
【数据结构】算法复杂度
c语言·开发语言·数据结构·学习·算法·leetcode·排序算法
程序员-King.1 小时前
day86——有效的字母异位词(LeetCode-242)
算法·字符串
xxxxxxllllllshi1 小时前
Java 代理模式深度解析:从静态到动态,从原理到实战
java·开发语言·笔记·算法·代理模式
Starry_hello world2 小时前
C++ 二分算法(1)
c++·算法·有问必答
小杨勇敢飞2 小时前
拼图小游戏开发日记 | Day3(已完结)
java·数据结构·算法
Guan jie2 小时前
10.6作业
数据结构·算法·排序算法
haidizym3 小时前
ssc-FinLLM 金融大模型 相关链接
人工智能·算法
Macre Aegir Thrym3 小时前
逻辑回归实践
算法·机器学习·逻辑回归
relis3 小时前
llama.cpp RMSNorm CUDA 优化分析报告
算法·llama