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。

相关推荐
U盘失踪了3 小时前
python JSONPath 表达式生成器
linux·windows·python
山烛6 小时前
决策树学习全解析:从理论到实战
人工智能·python·学习·算法·决策树·机器学习
没有梦想的咸鱼185-1037-16638 小时前
Python科研数据可视化技术
python·机器学习·信息可视化·数据分析
奔波霸的伶俐虫9 小时前
jeecg框架@Dict不生效问题
开发语言·python
徐赛俊10 小时前
# 自动定时运行Python爬虫脚本教程(Windows任务计划程序)
windows·爬虫·python
程序员秘密基地11 小时前
基于html,css,jquery,django,lstm,cnn,tensorflow,bert,推荐算法,mysql数据库
python·cnn·tensorflow·lstm·推荐算法
技术炼丹人11 小时前
从RNN为什么长依赖遗忘到注意力机制的解决方案以及并行
人工智能·python·算法
hqxstudying11 小时前
Java开发时出现的问题---语言特性与基础机制陷阱
java·jvm·python
仪器科学与传感技术博士12 小时前
python:机器学习中的分类与回归怎么理解
python·机器学习·分类
CodeCraft Studio12 小时前
使用 Aspose.OCR 将图像文本转换为可编辑文本
java·人工智能·python·ocr·.net·aspose·ocr工具