题解 | #名字的漂亮度#
名字的漂亮度
https://www.nowcoder.com/practice/02cb8d3597cf416d9f6ae1b9ddc4fde3
import java.util.*;
public class Main {
/**
* 给出一个字符串,该字符串仅由小写字母组成,定义这个字符串的“漂亮度”是其所有字母“漂亮度”的总和。
* 每个字母都有一个“漂亮度”,范围在1到26之间。没有任何两个不同字母拥有相同的“漂亮度”。字母忽略大小写。
* <p>
* 给出多个字符串,计算每个字符串最大可能的“漂亮度”。
* <p>
* 本题含有多组数据。
*
* @param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
int size = in.nextInt();
in.nextLine();
List<char[]> list = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
String str = in.nextLine();
list.add(str.toCharArray());
}
for (char[] chars : list) {
long max = getMaxBeauty(chars);
System.out.println(max);
}
}
}
public static int getMaxValue(String str) {
int[] array = new int[26];
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isLetter(c)) {
c = Character.toLowerCase(c);
array[c - 'a']++;
}
}
Arrays.sort(array);
int beauty = 26;
int sum = 0;
for (int i = array.length - 1; i >= 0 && array[i] > 0; i--) {
sum += (array[i] * beauty);
beauty--;
}
return sum;
}
public static int getMaxBeauty(char[] chars) {
int[] array = new int[26];
for (char c : chars) {
if (Character.isLetter(c)) {
c = Character.toLowerCase(c);
array[c - 'a']++;
}
}
Arrays.sort(array);
int beauty = 26;
int sum = 0;
for (int i = array.length - 1; i >= 0; i--) {
int count = array[i];
if (count == 0) {
break;
}
sum += (count * beauty);
beauty--;
}
return sum;
}
public static long getMax(char[] chars) {
HashMap<Character, Integer> map = new HashMap<>();
for (char c : chars) {
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
List<Map.Entry<Character, Integer>> entryList = new ArrayList<>(map.entrySet());
Collections.sort(entryList, (o1, o2) -> o2.getValue() - o1.getValue());
int beauty = 26;
long sum = 0;
for (Map.Entry<Character, Integer> entry : entryList) {
long v = (long) entry.getValue() * beauty;
sum += v;
beauty--;
}
return sum;
}
}
SHEIN希音公司福利 222人发布

查看7道真题和解析