LintCode 1742 · Orderly Queue (字符串分析好题)

1742 · Orderly Queue
Algorithms
Hard

Description
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.

1≤K≤S.length≤1000
S consists of lowercase letters only.
Example
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”.
Related Knowledge

解法1:BFS,每次把前k个字符中的一个移到后面,然后如果没有重复就放入queue, 但会超时。

解法2:
参考的网上的做法,
当k>1时,可以做到自由交换前k个字符中的任意两个字符,这样就可以实现冒泡排序了。也就是说,k>1时,通过若干次交换,可以将字符串达到排序的效果。
为什么当k>1时,可以做到自由交换前k个字符中的任意两个字符呢?
举例如下。s = “bcdaef”, k=2,我们想交换da。
bcdaef=>daefbc=>defbca=>efbcad=>bcadef

class Solution {
public:
    /**
     * @param s: a string
     * @param k: int
     * @return: the lexicographically smallest string
     */
    string orderlyQueue(string &s, int k) {
        string res = s;
        if (k > 1) {
            sort(res.begin(), res.end());
        } else {
            for (int i = 0; i < s.size(); i++) {
                res = min(res, s.substr(i) + s.substr(0, i));
            }
        }
        return res;
    }
};

你可能感兴趣的:(java,算法,数据结构,leetcode)