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);
        }
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值