leetcode 899. Orderly Queue

原题链接

You are given a string s and an integer k. You can choose one of the first k letters of s and append it at the end of the string.

Return the lexicographically smallest string you could have after applying the mentioned step any number of moves.

实际上如果k大于1,那么就会出现任意两个字符都能改变其在字符串中相对位置的情况,也就是能进行排序了。

如果k等于1,那么就找一个位置作为开始,遍历一下,找出字典序最小的那个排序就行。只是如果字符串中子串有规律,例如全是相同字符,或者重复出现ab之类的,那么就会出现最坏的情况,将这个最坏的情况优化掉。

复制代码
class Solution {
public:
    string orderlyQueue(string s, int k) {
        if (k ==0) return s;
        else if (k >1) {
            sort(s.begin(), s.end());
            return s;
        } else {
            int mn = 0,slen = s.size();
            for (int k = 1; k< slen; k++) {
                for(int l = 0; l < slen; l++) {
                    if (s[(k+l)%slen] < s[(mn+l)%slen]) {
                        mn = k;
                        break;
                    } else if (s[(k+l)%slen] > s[(mn+l)%slen]) {
                        break;
                    } else if (l == slen-1) return s.substr(mn) + s.substr(0, mn);
                }
            }
            return s.substr(mn) + s.substr(0, mn);
        }
    }
};
相关推荐
CoovallyAIHub11 分钟前
MSD-DETR:面向机车弹簧检测的可变形注意力Detection Transformer
算法·架构
CoovallyAIHub16 分钟前
不改权重、不用训练!BEM用背景记忆抑制固定摄像头误检,YOLO/RT-DETR全系有效
算法·架构·github
Struggle_975520 分钟前
算法知识-从递归入手三维动态规划
算法·动态规划
yuan1999726 分钟前
使用模糊逻辑算法进行路径规划(MATLAB实现)
开发语言·算法·matlab
不才小强29 分钟前
线性表详解:顺序与链式存储
数据结构·算法
CoovallyAIHub29 分钟前
上交+阿里 | Interactive ASR:Agent框架做语音识别交互纠错,1轮交互语义错误率降57%
算法·架构·github
Aaron158840 分钟前
8通道测向系统演示科研套件
人工智能·算法·fpga开发·硬件工程·信息与通信·信号处理·基带工程
计算机安禾1 小时前
【数据结构与算法】第42篇:并查集(Disjoint Set Union)
c语言·数据结构·c++·算法·链表·排序算法·深度优先
吃着火锅x唱着歌1 小时前
LeetCode 150.逆波兰表达式求值
linux·算法·leetcode
YuanDaima20481 小时前
二分查找基础原理与题目说明
开发语言·数据结构·人工智能·笔记·python·算法