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代码

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.执行结果

posted @ 2025-05-29 11:07  Geek0070  阅读(34)  评论(0)    收藏  举报