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);
        }
    }
};
相关推荐
佳木逢钺13 分钟前
从火灾模拟到系统热寂:一个双非运维如何用零 GPU 推导出多智能体系统的终极死锁
人工智能·python·算法·多智能体
垆边人似月.17 分钟前
网格最小代价路径,总代价不超过 budget
算法
虚无的纽扣18 分钟前
【力扣刷题】第五天:将 x 减到 0 的最小操作数、最大连续1的个数 III
算法·leetcode·职场和发展
C++ 老炮儿的技术栈22 分钟前
char 造成的数据溢出
linux·服务器·c语言·c++·算法·c
sqc233sqc37 分钟前
第 J8 周:ResNeXt-50 算法解析
人工智能·算法
hanlin0310 小时前
刷题笔记:力扣第32题-最长有效括号
笔记·算法·leetcode
All for pursuit.11 小时前
【动态规划-21】312.戳气球
数据结构·c++·算法·leetcode·动态规划
碧海银沙音频科技研究院13 小时前
基于炬芯ATS3089X自研AEC声学回声消除算法
算法
通问AI13 小时前
在两台 Mac Studio 上跑 800B 模型:MLX + RDMA over Thunderbolt 实测与四道门选型法
算法
ZywOo62313 小时前
《算法竞赛进阶指南》0x03 前缀和与差分
算法