题解 | #名字的漂亮度#

名字的漂亮度

http://www.nowcoder.com/practice/02cb8d3597cf416d9f6ae1b9ddc4fde3

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int N = Integer.valueOf(scan.nextLine().trim());
        for (int i = 0; i < N; i++) {
            String str = scan.nextLine();
            process(str);
        }
    }
    public static void process(String str) {
        int[] nums = new int[26];
        HashSet<Character> hashSet = new HashSet<>();
        char[] chrs = str.toCharArray();
        for (int i = 0; i < chrs.length; i++) {
            nums[chrs[i] - 'a']++;
            hashSet.add(chrs[i]);
        }
        char[] chrSet = new char[hashSet.size()];
        int index = 0;
        for (char chr : hashSet) {
            chrSet[index++] = chr;
        }
        heapSort(chrSet, nums);
        int ans = 0;
        int acc = 26;
        for (int i = 0; i < chrSet.length; i++) {
            ans += nums[chrSet[i] - 'a'] * acc;
            acc--;
        }
        System.out.println(ans);
    }
    public static void heapSort(char[] chrs, int[] nums) {
        if (null == chrs || chrs.length < 2) {
            return;
        }
        for (int i = 0; i < chrs.length; i++) {
            heapInsert(chrs, nums, i);
        }
        int heapSize = chrs.length;
        swap(chrs, 0, --heapSize);
        while (heapSize > 0) {
            heapify(chrs, nums, 0, heapSize);
            swap(chrs, 0, --heapSize);
        }
    }
    public static void heapInsert(char[] chrs, int[] nums, int index) {
        while (nums[chrs[index] - 'a'] < nums[chrs[(index - 1) / 2] - 'a']) {
            swap(chrs, index, (index - 1) / 2);
            index = (index - 1) / 2;
        }
    }
    public static void heapify(char[] chrs, int[] nums, int index, int heapSize) {
        int left = index * 2 + 1;
        while (left < heapSize) {
            int smallest = left + 1 < heapSize && nums[chrs[left + 1] - 'a'] < nums[chrs[left] - 'a'] ? left + 1 : left;
            smallest = nums[chrs[smallest] - 'a'] < nums[chrs[index] - 'a'] ? smallest : index;
            if (smallest == index) {
                break;
            }
            swap(chrs, index, smallest);
            index = smallest;
            left = index * 2 + 1;
        }
    }
    public static void swap(char[] chrs, int p1, int p2) {
        char tmp = chrs[p1];
        chrs[p1] = chrs[p2];
        chrs[p2] = tmp;
    }
}
全部评论

相关推荐

实习挂完提前批挂_提前批挂完秋招挂:我是来结束这个秋招的😤
点赞 评论 收藏
分享
铁锈不腻玩家:下面那个袁先生删了,问他怎么回事,头像都换不明白
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务