Leetcode 159. 至多包含两个不同字符的最长子串
本文最后更新于384 天前,其中的信息可能已经过时,如有错误请发送邮件到2446865563@qq.com

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

觉得有帮助可以投喂下博主哦~感谢!

作者:geek007

转载请注明文章地址及作者哦~
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇