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。

相关推荐
M1A126 分钟前
Python数据结构操作:全面解析与实践
后端·python
扑克中的黑桃A31 分钟前
Python-打印杨辉三角
python
程序员三藏1 小时前
如何使用Jmeter进行压力测试?
自动化测试·软件测试·python·测试工具·jmeter·测试用例·压力测试
carpell2 小时前
【语义分割专栏】3:Segnet原理篇
人工智能·python·深度学习·计算机视觉·语义分割
24K纯学渣2 小时前
Python编码格式化之PEP8编码规范
开发语言·ide·python·pycharm
怒视天下2 小时前
零基础玩转Python生物信息学:数据分析与算法实现
开发语言·python
zhanshuo2 小时前
Python元组黑科技:3招让数据安全暴增200%,学生管理系统实战揭秘!
python
空中湖2 小时前
免费批量图片格式转换工具
图像处理·python·程序人生
Mantanmu2 小时前
Python训练day40
人工智能·python·机器学习
天天爱吃肉82183 小时前
新能源汽车热管理核心技术解析:冬季续航提升40%的行业方案
android·python·嵌入式硬件·汽车