zoukankan      html  css  js  c++  java
  • 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. 1 <= K <= S.length <= 1000
    2. S consists of lowercase letters only.

    Approach #1: String. [Java]

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

      

    Analysis:

    1. When K == 1: 

    We can only rotate the whole string. There are S.length different states and we return the lexicographically smallest string.

    2. When K >= 2 you can swap any 2 character in the string:

    Assume u have "abcdefg", put "b" into tail, and ten paut "acdefg" into the tail. Then you have "bacdefg". Based on this, u can swap first a and b.

    Because the string is a ring, u can sliding it. This means you can swap any 2 character in the string. e.g. "abcdefg" -> "acdefgb" -> "cadefgb".

    Reference:

    https://leetcode.com/problems/orderly-queue/discuss/165857/Java-Simple-Solution-12-ms

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    经典语录二
    squid通过正向代理访问互联网
    jQuery
    CSS常用属性
    css基本选择器
    html标签
    事件驱动模型与IO模型
    协程
    进程与线程
    软件安装 yum rpm
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10797489.html
Copyright © 2011-2022 走看看