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);
        }
    }
};
相关推荐
2401_891482177 小时前
多平台UI框架C++开发
开发语言·c++·算法
88号技师8 小时前
2026年3月中科院一区SCI-贝塞尔曲线优化算法Bezier curve-based optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
t198751288 小时前
三维点云最小二乘拟合MATLAB程序
开发语言·算法·matlab
无敌昊哥战神8 小时前
【LeetCode 257】二叉树的所有路径(回溯法/深度优先遍历)- Python/C/C++详细题解
c语言·c++·python·leetcode·深度优先
x_xbx8 小时前
LeetCode:148. 排序链表
算法·leetcode·链表
Darkwanderor8 小时前
三分算法的简单应用
c++·算法·三分法·三分算法
2401_831920749 小时前
分布式系统安全通信
开发语言·c++·算法
WolfGang0073219 小时前
代码随想录算法训练营 Day17 | 二叉树 part07
算法
温九味闻醉9 小时前
关于腾讯广告算法大赛2025项目分析1 - dataset.py
人工智能·算法·机器学习
炽烈小老头9 小时前
【 每天学习一点算法 2026/03/23】数组中的第K个最大元素
学习·算法·排序算法