Leetcode 2904. Shortest and Lexicographically Smallest Beautiful String

  • [Leetcode 2904. Shortest and Lexicographically Smallest Beautiful String](#Leetcode 2904. Shortest and Lexicographically Smallest Beautiful String)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

这一题其实没啥好多说啥的,就是一个滑动窗口的思路,用滑动窗口考察每一个beautiful string的长度以及其是否为字母序最小即可。

2. 代码实现

给出python代码实现如下:

python 复制代码
class Solution:
    def shortestBeautifulSubstring(self, s: str, k: int) -> str:
        ans = ""
        n = len(s)
        i, j, cnt = 0, 0, 0
        while i < n:
            while j < n and cnt < k:
                if s[j] == "1":
                    cnt += 1
                j += 1
            if cnt < k:
                break
            if ans == "" or len(ans) > len(s[i:j]) or (len(ans) == len(s[i:j]) and ans > s[i:j]):
                ans = s[i:j]
            if s[i] == "1":
                cnt -= 1
            i += 1
        return ans  

提交代码评测得到:耗时46ms,占用内存16.2MB。

相关推荐
南汐汐月5 分钟前
重生归来,我要成功 Python 高手--day33 决策树
开发语言·python·决策树
lzjava202411 分钟前
Spring AI使用知识库增强对话功能
人工智能·python·spring
B站_计算机毕业设计之家28 分钟前
深度血虚:Django水果检测识别系统 CNN卷积神经网络算法 python语言 计算机 大数据✅
python·深度学习·计算机视觉·信息可视化·分类·cnn·django
Q_Q51100828530 分钟前
python+django/flask的校园活动中心场地预约系统
spring boot·python·django·flask·node.js·php
工会主席-阿冰36 分钟前
数据索引是无序时,直接用这个数据去画图的话,显示的图是错误的
开发语言·python·数据挖掘
Naiva43 分钟前
【小技巧】PyCharm建立项目,VScode+CodeX+WindowsPowerShell开发Python pyQT6 (二)
vscode·python·pycharm
Lucifer__hell1 小时前
【python+tkinter】图形界面简易计算器的实现
开发语言·python·tkinter
2301_812914871 小时前
py day34 装饰器
开发语言·python
我的xiaodoujiao2 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 24--数据驱动--参数化处理 Excel 文件 1
python·学习·测试工具·pytest
开心-开心急了2 小时前
关于Flutter与Qt for python 的一些技术、开源、商用等问题
开发语言·python·qt·flutter