当前位置:网站首页>LeetCode刷题笔记:899.有序队列
LeetCode刷题笔记:899.有序队列
2022-08-07 06:40:00 【LeBron Le】
1. 问题描述
给定一个字符串 s 和一个整数 k 。你可以从 s 的前 k 个字母中选择一个,并把它加到字符串的末尾。
返回 在应用上述步骤的任意数量的移动后,字典上最小的字符串 。
2. 解题思路
分两种情况讨论:
① 当 k = 1 时,每次只能将字符串的第一个元素移动到字符串的末尾,即轮转整个字符串,取字典序最小即可。
② 当 k >= 2 时,首先单独拎出字符串第一个元素 s[0],接着每次将剩下的字符串中的第一个元素 s[1] 不断移动到字符串末尾,即可轮转整个字符串,然后在适当的适合插入 s[0]。
3. 代码实现
class Solution {
public String orderlyQueue(String s, int k) {
StringBuffer sb = new StringBuffer(s);
if (k == 1) {
String res = s;
for (int i = 0; i < s.length() - 1; i++) {
char head = sb.charAt(0);
sb.deleteCharAt(0);
sb.append(head);
if (sb.toString().compareTo(res) < 0) {
res = sb.toString();
}
}
return res;
} else {
char[] c = s.toCharArray();
Arrays.sort(c);
return String.valueOf(c);
}
}
}
边栏推荐
猜你喜欢
随机推荐
The permutation sequence of the 60th question in C language.Breadth-first search, simple division positioning
This beta version of Typora is expired
DOM,SAX,JDOM,DOM4J四种方法对比总结
QGIS最受欢迎的20个插件
Ali cloud message service, SMS
VoLTE Basic Self-Learning Series | What is Forking in SIP and IMS
标签:对顶堆
servlet 教程 1:环境搭建和新建 servlet 项目
数组去重的几种办法
0-1背包问题
Completed - based on SSM online movie booking system
【n子棋】
VoLTE Basic Self-Learning Series | VoLTE Network Architecture
VoLTE基础自学系列 | 汇总
VoLTE Basic Self-Learning Series | IMS Network Overview
查找一个复杂对象或数组里面是否包含某一个值
基于ESP32的蓝牙鼠标键盘(一)BleKeyboard.h函数解析
shell之正则表达式及三剑客grep命令
微信小程序--》小程序全局配置和详解下拉刷新和上拉触底页面事件
VoLTE基础自学系列 | IMS网络中的IP层路由寻址过程(注册流程中的实现)









