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。

相关推荐
小镇敲码人6 分钟前
深入剖析华为CANN框架下的Ops-CV仓库:从入门到实战指南
c++·python·华为·cann
摘星编程25 分钟前
深入理解CANN ops-nn BatchNormalization算子:训练加速的关键技术
python
魔芋红茶26 分钟前
Python 项目版本控制
开发语言·python
lili-felicity33 分钟前
CANN批处理优化技巧:从动态批处理到流水线并行
人工智能·python
一个有梦有戏的人35 分钟前
Python3基础:进阶基础,筑牢编程底层能力
后端·python
摘星编程1 小时前
解析CANN ops-nn中的Transpose算子:张量维度变换的高效实现
python
Liekkas Kono1 小时前
RapidOCR Python 贡献指南
开发语言·python·rapidocr
玄同7651 小时前
Python 后端三剑客:FastAPI/Flask/Django 对比与 LLM 开发选型指南
人工智能·python·机器学习·自然语言处理·django·flask·fastapi
爱吃泡芙的小白白1 小时前
环境数据多维关系探索利器:Pairs Plot 完全指南
python·信息可视化·数据分析·环境领域·pairs plot