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);
        }
    }
};
相关推荐
Da Da 泓25 分钟前
LinkedList模拟实现
java·开发语言·数据结构·学习·算法
海琴烟Sunshine32 分钟前
Leetcode 14. 最长公共前缀
java·服务器·leetcode
未知陨落33 分钟前
LeetCode:68.寻找两个正序数组的中位数
算法·leetcode
努力学习的小廉3 小时前
我爱学算法之—— 模拟(下)
c++·算法
海琴烟Sunshine4 小时前
Leetcode 26. 删除有序数组中的重复项
java·算法·leetcode
PAK向日葵4 小时前
【算法导论】NMWQ 0913笔试题
算法·面试
PAK向日葵4 小时前
【算法导论】DJ 0830笔试题题解
算法·面试
PAK向日葵4 小时前
【算法导论】LXHY 0830 笔试题题解
算法·面试
麦麦麦造5 小时前
DeepSeek突然发布 V3.2-exp,长文本能力加强,价格进一步下探
算法
lingran__6 小时前
速通ACM省铜第十七天 赋源码(Racing)
c++·算法