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。

相关推荐
咖啡续命又一天22 分钟前
python 自动化采集 ChromeDriver 安装
开发语言·python·自动化
松果集1 小时前
【1】数据类型2
python
且慢.5892 小时前
命令行的学习使用技巧
python
海琴烟Sunshine2 小时前
leetcode 66.加一 python
python·算法·leetcode
罗橙7号2 小时前
【pyTorch】关于PyTorch的高级索引机制理解
人工智能·pytorch·python
B站计算机毕业设计之家2 小时前
智能监控项目:Python 多目标检测系统 目标检测 目标跟踪(YOLOv8+ByteTrack 监控/交通 源码+文档)✅
python·yolo·目标检测·目标跟踪·智慧交通·交通·多目标检测
江上月5132 小时前
django与vue3的对接流程详解(下)
后端·python·django
nightunderblackcat3 小时前
四大名著智能可视化推演平台
前端·网络·爬虫·python·状态模式
小蕾Java3 小时前
PyCharm入门级详细使用手册(Python新手快速上手篇)
ide·python·pycharm
动能小子ohhh3 小时前
AI智能体(Agent)大模型入门【9】--如何在pycharm等其他编译软件调用ocr工具【只写后端代码不演示】
人工智能·python·深度学习·机器学习·pycharm·ocr