题解 | #名字的漂亮度#
名字的漂亮度
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; } }