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。

相关推荐
山海云端有限公司10 分钟前
实战指南:用豆包图片生成API快速搭建AI绘画能力
python·ai绘画·api调用·图片生成·豆包api
ganbingfenxiang17 分钟前
山西干冰零售
大数据·人工智能·python·零售
薛定猫AI21 分钟前
【深度解析】GLM-5.2 与 Z-Code:AI 编程智能体的原理拆解与 Python 调用实战
开发语言·人工智能·python
冰暮流星25 分钟前
flask之定义URL
后端·python·flask
蒟蒻的贤1 小时前
python搭建MiniDL
开发语言·python·深度学习
老前端的功夫1 小时前
【Java从入门到入土】47:构建工具:Maven与Gradle的战争
java·python·maven
yang_coder1 小时前
juypter notebook启动ssl报错的处理记录
python·jupyter
江华森2 小时前
exp01_Python_数据类型
开发语言·python
大鱼>2 小时前
模型可解释性:特征重要性/SHAP/LIME
人工智能·python·机器学习·lstm
代码不接地2 小时前
【时间序列预测】0.时间序列任务知识地图
python·ai编程