899. Orderly Queue

原题链接

899. Orderly Queue

题目描述

A string S of lowercase letters is given. Then, we may make any number of moves.

In each move, we choose one of the first K letters (starting from the left), remove it, and place it at the end of the string.

Return the lexicographically smallest string we could have after any number of moves.
Example 1:

Input: S = "cba", K = 1
Output: "acb"
Explanation: 
In the first move, we move the 1st character ("c") to the end, obtaining the string "bac".
In the second move, we move the 1st character ("b") to the end, obtaining the final result "acb".

Example 2:

Input: S = "baaca", K = 3
Output: "aaabc"
Explanation: 
In the first move, we move the 1st character ("b") to the end, obtaining the string "aacab".
In the second move, we move the 3rd character ("c") to the end, obtaining the final result "aaabc".

Note:
1 <= K <= S.length <= 1000
S consists of lowercase letters only.

这个题目的关键是要想清楚,当K>1的时候,相当于任意两个相邻的数都能交换,任意两个相邻的数都能交换,可以类比到冒泡排序,这是冒泡排序的主要思想。
下边证明:

假设数组中任意两个相邻的数c[i] = a, 和c[j] = b(j = i + 1),我们的目标是将其交换:下面是变幻的过程:
XXXab***
  |  (将第一个移到最后,循环3次)
ab***XXX
  |  (将第二个移到最后)
a***XXXb
  |  (将第一个移到最后)
***XXXba
  |  (将第一个移到最后,循环3次)
XXXba***
成功!

说明我们已经能将任意两个相邻的数进行交换,因此,我们可以用冒泡排序,也就是能直接对其进行排序。

代码:


class Solution {
    public String orderlyQueue(String S, int K) {
        if(K == 0 || S == null) {
            return S;
        }
        if(K == 1) {
            int len = S.length();
            String res = new String(S);
            for(int i = 0; i < len; i++) {
                S = S.substring(1) + S.charAt(0);
                if(S.compareTo(res) < 0) {
                    res = S;
                }
            }
            return res;
        }else {
            char[] temp = S.toCharArray();
            Arrays.sort(temp);
            return String.valueOf(temp);
        }

    }   
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值