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)
  • 相关阅读:
    Sql server 经典常用函数
    Sql Server 时间格式化
    eval解析JSON中的注意点
    SQL Server 数据库try catch 存储过程
    SQL 添加索引
    sql中的begin catch 。。。end catch 的用法
    常用正则表达式
    css3实现背景渐变
    CacheHelper
    星座运势(等)接口控制器
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10797489.html
Copyright © 2011-2022 走看看