当前位置:网站首页>[899] ordered queue

[899] ordered queue

2022-07-06 12:25:00 Vigorous waist Nuo dance

Topic summary
Given a string . Within the limits of the rules , Adjust it to the minimum order in my dictionary .

subject

Given a string s And an integer k . You can start your s Before k Select one of the letters , And add it to the end of the string .

return After applying any number of movements of the above steps , The smallest string in the dictionary .

source : Power button (LeetCode)
link :https://leetcode.cn/problems/orderly-queue
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

Example 1

Input :s = “cba”, k = 1
Output :“acb”
explain :
In the first step , We'll take the first character (“c”) Move to the end , Get string “bac”.
In the second step , We'll take the first character (“b”) Move to the end , Get the final result “acb”.

Example 2

Input :s = “baaca”, k = 3
Output :“aaabc”
explain :
In the first step , We'll take the first character (“b”) Move to the end , Get string “aacab”.
In the second step , We'll take the third character (“c”) Move to the end , Get the final result “aaabc”.

    public String orderlyQueue(String s, int k) {
    
        /* When only one character can be moved . You can treat the string as a circular linked list */
        if(k==1){
    
            String ans=s;
            /* Then you need to determine the dictionary order of the string starting from any position */
            for (int i = 0; i < s.length(); i++) {
    
                String temp=s.substring(i)+s.substring(0,i);
                if(temp.compareTo(ans)<0)
                    ans=temp;
            }
            return ans;
        }
        /*k>=2 When . It can be proved : You can exchange two characters of a given string at will . That is, the alphabetical order of the final string can be adjusted to the lowest */
        else{
    
            /* After being converted into a character array, you can sort */
            char[] ca = s.toCharArray();
            /*sort Functions are in ascending order by default */
            Arrays.sort(ca);
            /* Don't try to match character arrays toString: What is returned is the type and the corresponding hash code . It seems that except for string Of tostring It's overloaded . Others are inherited directly object*/
            return new String(ca);
        }
    }

原网站

版权声明
本文为[Vigorous waist Nuo dance]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060913547864.html