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

1.题目基本信息

1.1.题目描述

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

1.2.题目地址

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

2.解题方法

2.1.解题思路

滑动窗口

2.2.解题步骤

第一步,构建维护变量。left,right俩指针维护一个滑动窗口;map_维护滑动窗口中每个字符的最右侧的字符串的索引;currentLength维护当前的不同字符子串的长度

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

3.解题代码

python代码

class Solution:
    # 重点: 双指针+map记录滑动窗口内各字符的最右侧索引
    # 注意: 区分maxLength和currentLength
    def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
        if k==0:
            return 0
        length=len(s)
        # 第一步,构建维护变量。left,right俩指针维护一个滑动窗口;map_维护滑动窗口中每个字符的最右侧的字符串的索引;currentLength维护当前的不同字符子串的长度
        left,right=0,0
        map_={}
        currentLength=0
        # 第二步,滑动窗口进行滑动,更新currentLength和maxLength
        maxLength=1
        for i in range(length):
            map_[s[i]]=i
            right=i
            if len(map_)>k:                
                # 删除最小索引的字符
                minIndex=min(map_.values())
                for item in map_.copy().items():
                    if item[1]==minIndex:
                        # 更新滑动窗口左侧指针
                        left=map_[item[0]]+1
                        del map_[item[0]]
                        break
                currentLength=right-left+1
            else:
                currentLength+=1
            maxLength=max(maxLength,currentLength)
        return maxLength

4.执行结果

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

作者:geek007

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

发送评论 编辑评论


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