LeetCode-1370. Ascending and descending string (Java implementation)

LeetCode question number: 1370. Ascending and descending strings

Description: Given an unordered array, find the largest difference between adjacent elements after the array is sorted. If the number of array elements is less than 2, it returns 0;

Example 1:

Input: [3,6,9,1]
Output: 3
Explanation: The sorted array is [1,3,6,9], where adjacent elements (3,6) and (6,9) exist between The maximum difference is 3.

 

 //采用桶排序
    public static String sortString(String s) {
        //存放26字母的桶
        int[] count = new int[26];
        char[] c = s.toCharArray();
        //存储计算的结果
        StringBuilder str = new StringBuilder();
        //把s中的字符分别放到对应的桶里,统计字母个数
        for (char c1 : c) {
            count[c1 - 'a']++;
        }
        while (str.length() != s.length()) {
            //先从左往右找,遍历26个桶,如果当前桶不为空,
            //就从当前桶里拿出一个元素出来
            for (int i = 0; i < count.length; i++) { //步骤123
                if (count[i] > 0) {
                    str.append((char) (i + 'a'));//转成对应的字母
                    count[i]--; //拿出之后桶中元素的个数要减1
                }
            }
            //从右往左拿,同上
            for (int j = count.length - 1; j >= 0; j--) {//步骤456
                if (count[j] > 0) {
                    str.append((char) (j + 'a'));//转成对应的字母
                    count[j]--;
                }
            }
        }
        //把结果转化为字符串
        return str.toString();

Past review:

[1] LeetCode-409. The longest palindrome (implemented by Goland)

[2] LeetCode-459. Repeated substring (implemented by Goland)

[3] LeetCode-53. Maximum subsequence sum (implemented by Goland)


❤If the article is helpful to you, please click like at the top right corner of the article or at the end of the article! (づ ̄ 3 ̄)づ 

❤If you like the articles shared by the white rabbit, please pay attention to the white rabbit! (๑′ᴗ‵๑)づ╭❤~

❤If you have any questions about the article, please leave a message below or join the group to discuss [group number: 708072830]

❤In view of the limited personal experience, all opinions and technical research points, if you have any objections, please reply directly to the discussion (do not make offensive remarks)

Guess you like

Origin blog.csdn.net/weixin_43970743/article/details/110189600