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。

相关推荐
久绊A20 分钟前
Python 基本语法的详细解释
开发语言·windows·python
Hylan_J4 小时前
【VSCode】MicroPython环境配置
ide·vscode·python·编辑器
莫忘初心丶4 小时前
在 Ubuntu 22 上使用 Gunicorn 启动 Flask 应用程序
python·ubuntu·flask·gunicorn
失败尽常态5237 小时前
用Python实现Excel数据同步到飞书文档
python·excel·飞书
2501_904447747 小时前
OPPO发布新型折叠屏手机 起售价8999
python·智能手机·django·virtualenv·pygame
青龙小码农7 小时前
yum报错:bash: /usr/bin/yum: /usr/bin/python: 坏的解释器:没有那个文件或目录
开发语言·python·bash·liunx
大数据追光猿7 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
Leuanghing7 小时前
【Leetcode】11. 盛最多水的容器
python·算法·leetcode
xinxiyinhe8 小时前
如何设置Cursor中.cursorrules文件
人工智能·python
诸神缄默不语9 小时前
如何用Python 3自动打开exe程序
python·os·subprocess·python 3