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。

相关推荐
一个闪现必杀技3 分钟前
Python入门--函数
开发语言·python·青少年编程·pycharm
小鹿( ﹡ˆoˆ﹡ )23 分钟前
探索IP协议的神秘面纱:Python中的网络通信
python·tcp/ip·php
卷心菜小温38 分钟前
【BUG】P-tuningv2微调ChatGLM2-6B时所踩的坑
python·深度学习·语言模型·nlp·bug
陈苏同学1 小时前
4. 将pycharm本地项目同步到(Linux)服务器上——深度学习·科研实践·从0到1
linux·服务器·ide·人工智能·python·深度学习·pycharm
唐家小妹1 小时前
介绍一款开源的 Modern GUI PySide6 / PyQt6的使用
python·pyqt
羊小猪~~2 小时前
深度学习项目----用LSTM模型预测股价(包含LSTM网络简介,代码数据均可下载)
pytorch·python·rnn·深度学习·机器学习·数据分析·lstm
Marst Code2 小时前
(Django)初步使用
后端·python·django
985小水博一枚呀2 小时前
【对于Python爬虫的理解】数据挖掘、信息聚合、价格监控、新闻爬取等,附代码。
爬虫·python·深度学习·数据挖掘
立秋67892 小时前
Python的defaultdict详解
服务器·windows·python
萧鼎3 小时前
Python第三方库选择与使用陷阱避免
开发语言·python