题解 | #名字的漂亮度#

名字的漂亮度

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) {
        BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
        StringBuffer str = new StringBuffer();
        String a;
        String[] names;
        int n, i = 0, j, k, l, max = 0, m, pretty;
        try {
            a = r.readLine();
            n = count(a);//解析获得有多少行字符串
            names = new String[n];//初始化数组
            while ((a = r.readLine()) != null && !a.isEmpty() && i < n) {
                names[i++] = a;//存入字符串数组
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        int[] nums;//将字符串中各个字符有多少个存入nums数组
        int[] cnt;//每种个数对应有多少种字符
        i = 0;
        for (; i < n; i++) {
            char[] chs = names[i].toCharArray();
            j = 0;
            l = chs.length;
            nums = new int[27];
            while (j <
                    l) {//遍历字符串将个数统计,a对应索引1,z对应索引26
                nums[chs[j] - 'a' + 1]++;//出现次数递增
                j++;
            }
            j = 1;
            while (j < 27) {//得到最大的出现次数,以便cnt数组初始化
                max = Math.max(max, nums[j]);
                j++;
            }
            cnt = new int[max +
                          1];//初始化数组,以出现次数作为下标索引1~max
            j = 1;
            while (j <
                    27) {//遍历nums,将每种次数出现字符的个数统计进入cnt,1次~max次
                m = nums[j];
                if (m != 0) cnt[m]++;
                j++;
            }
            j = 26;//最大漂亮度26,依次递减
            m = max;
            pretty = 0;
            while (m > 0) {//遍历cnt数组
                for (k = 0; k < cnt[m]; k++) {
                    pretty += m *
                              j--;//出现次数最多的字符*较大的漂亮度,递减j,随着出现次数的递减,相同出现次数的字符无漂亮度优先级,按次数遍历
                }
                m--;
            }
            str.append(pretty).append("\n");
        }
        System.out.print(str);
    }

    //根据字符串获得数字
    private static int count(String string) {
        char[] chs = string.toCharArray();
        int i = 0, l = chs.length, n = 0;
        while (i < l) {
            if (chs[i] == '\u0000' || chs[i] == ' ') {
                i++;
                continue;
            }
            n *= 10;
            n += chs[i] - '0';
            i++;
        }
        return n;
    }
}

全部评论

相关推荐

04-28 19:31
门头沟学院 Java
真烦好烦真烦:可恶的二手车贩子,居然对我们门头沟学院的人这么没礼貌
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务