题解 | #名字的漂亮度#

名字的漂亮度

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;
    }
}

全部评论

相关推荐

08-23 20:17
四川大学 C++
xxxzsfa:技术栈可以参考我这个给写,把知识点写出来起码能让面试官知道你是知道这个点的,不会的知识点可以不写,简历上写了但又答不上来就很尴尬了,可以给技术栈中的知识点和项目中的难点亮点加粗,学历不错,肯定会有大厂面的,刚开始可以先投中小厂练手,拿个offer保底再去面大厂,秋招可以正式和实习一起找,找工作是个需要长期坚持的过程,加油查看图片
点赞 评论 收藏
分享
码农索隆:邮件那么小的内存,把邮箱都干满了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务