当前位置:网站首页>Leetcode 899. An orderly queue
Leetcode 899. An orderly queue
2022-08-03 20:12:00 【Luna who can program】
Given a string s and an integer k .You can choose one of the first k letters of s and add it to the end of the string.
returns the lexicographically smallest string after applying any number of moves from the above steps.
Example 1:
Input: s = "cba", k = 1
Output: "acb"
Explanation:
In the first step, we move the first character ("c") to the end, to get the string "bac".
In the second step, we move the first character ("b") to the end to get the final result "acb".
Example 2:
Input: s = "baaca", k = 3
Output: "aaabc"
Explanation:
In the first step, we move the first character ("b") to the end, to get the string "aacab".
In the second step, we move the third character ("c") to the end to get the final result "aaabc".
Tip:
1 <= k <= S.length <= 1000
s consists of lowercase letters only.
Thinking:
When k==1, the original string is regarded as a ring, the first character is placed at the end every time from the beginning to the end, and the lexicographical order among these characters is saved and simulated directly.
When k>=2, after a limited number of operations, it must be in ascending order, because we can choose the largest one in the first k every time and put it at the end, which is very troublesome in practice, but withThe result of sorting is the same, so you can return directly to sort.
class Solution {public:string orderlyQueue(string s, int k) {if(k>1){sort(s.begin(),s.end());return s;}string ans=s;for(int i=0;i<s.size();++i){s=string{s.begin()+1,s.end()}+s[0];span>ans=min(ans,s);}return ans;}};
边栏推荐
猜你喜欢
一种能有效缓解环境噪声对音频质量干扰的方案
async 和 await 原来这么简单
若依集成easyexcel实现excel表格增强
Pytorch GPU 训练环境搭建
Advantages and Disadvantages of Blind and Buried Via PCB Stacked Via Design
622 设计循环队列——Leetcode天天刷【循环队列,数组模拟,双指针】(2022.8.2)
宁德时代2号人物黄世霖辞任副董事长:身价1370亿
调用EasyCVR云台控制接口时,因网络延迟导致云台操作异常该如何解决?
李沐动手学深度学习V2-BERT微调和代码实现
Internet Download Manager简介及下载安装包,IDM序列号注册问题解决方法
随机推荐
数学之美 第六章——信息的度量和作用
1161 最大层内元素和——Leetcode天天刷【BFS】(2022.7.31)
【飞控开发高级教程3】疯壳·开源编队无人机-定高、定点、悬停
C中的数据存储
The sword refers to Offer II 044. The maximum value of each level of the binary tree-dfs method
花 30 美金请 AI 画家弄了个 logo,网友:画得非常好,下次别画了!
Pytorch GPU 训练环境搭建
Go语言为任意类型添加方法
单调栈及其应用
leetcode 2119. Numbers reversed twice
Benchmarking Lane-changing Decision-making for Deep Reinforcement Learning
友宏医疗与Actxa签署Pre-M Diabetes TM 战略合作协议
leetcode 072. Finding Square Roots
leetcode 16. 数值的整数次方(快速幂+递归/迭代)
力扣707-设计链表——链表
高位套牢机构,用友网络的信任危机是如何产生的?
leetcode 剑指 Offer 58 - II. 左旋转字符串
涨薪5K必学高并发核心编程,限流原理与实战,分布式计数器限流
Why BI software can't handle correlation analysis
开源生态研究与实践| ChinaOSC