899. Orderly Queue
发布日期:2021-05-09 02:51:26 浏览次数:16 分类:博客文章

本文共 1883 字,大约阅读时间需要 6 分钟。

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 = 1Output: "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 = 3Output: "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:

 

上一篇:916. Word Subsets
下一篇:856. Score of Parentheses

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2025年04月20日 13时53分12秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章

主定理的应用 2019-03-11
动态规划算法的迭代实现 2019-03-11
最优装载问题 2019-03-11
最大团问题 2019-03-11
圆排列问题 2019-03-11
课程总结 2019-03-11
认识CMake及应用 2019-03-11
CMake的主体框架 2019-03-11
微积分(三) 2019-03-11
Oracle 2019-03-11
软件工程应用 2019-03-11
数据科学 2019-03-11
函数与高级变量 2019-03-11
键盘事件 2019-03-11
2020-11月计划实施表 2019-03-11
折线图 2019-03-11
常识: 2019-03-11
注册页面案例 2019-03-11
np.bincount(x)的简单解释 2019-03-11
一些面试的准备的回答 2019-03-11