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。

相关推荐
AAA_bo13 分钟前
liunx安装canda、python、nodejs、git,随后部署私有网页内容提取工具--JinaReader全攻略
linux·python·ubuntu·typescript·aigc·python3.11·jina
高洁0119 分钟前
DNN案例一步步构建深层神经网络(3)
python·深度学习·算法·机器学习·transformer
AI_567823 分钟前
Jupyter交互式数据分析的效率革命
开发语言·python
superman超哥25 分钟前
仓颉语言中并发集合的实现深度剖析与高性能实践
开发语言·后端·python·c#·仓颉
superman超哥26 分钟前
仓颉语言中原子操作的封装深度剖析与无锁编程实践
c语言·开发语言·后端·python·仓颉
拾贰_C27 分钟前
【Anaconda | Python | pytorch】sklearn scikit-learn 报错:
pytorch·python·sklearn
叶子丶苏30 分钟前
第十八节_PySide6基本窗口控件深度补充_剪贴板与拖曳功能(QMimeData 类) 上篇
python·pyqt
酷酷的佳36 分钟前
python--面向对象(3)
python
百锦再1 小时前
Python实现开源AI模型引入及测试全过程
人工智能·python·ai·开源·aigc·模型·自然语言
有时有晌1 小时前
影视解说混剪工具
python·影视解说·影视混剪