题解 | #名字的漂亮度#
名字的漂亮度
http://www.nowcoder.com/practice/02cb8d3597cf416d9f6ae1b9ddc4fde3
思路:把每个名字拆成字母放入Map,key为字母,value为次数,对map进行降序排序后进行计算。每个字母出现次数cnt * (26 - i)加起来就是名字的漂亮度
sum += entry.getValue() * (26 - j);
import java.util.*; import java.util.Map.Entry; public class BeautyOfName { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNextInt()) { int num = sc.nextInt(); int[] beaulty = new int[num]; for (int i = 0; i < num; i++) { String name = sc.next(); beaulty[i] = calBeaultyOfName(name); } for (int i = 0; i < num; i++) { System.out.println(beaulty[i]); } } } private static int calBeaultyOfName(String name) { Map<Character, Integer> letterCntMap = new TreeMap<>(); char[] nameCharArr = name.toCharArray(); for (int i = 0; i < nameCharArr.length; i++) { char c = Character.toLowerCase(nameCharArr[i]); if (letterCntMap.keySet().contains(c)) { letterCntMap.put(c, letterCntMap.get(c) + 1); } else { letterCntMap.put(c, 1); } } int j = 0; int sum = 0; List<Entry<Character, Integer>> list = new ArrayList<Entry<Character, Integer>>(letterCntMap.entrySet()); Collections.sort(list, new Comparator<Entry<Character, Integer>>() { @Override public int compare(Entry<Character, Integer> o1, Entry<Character, Integer> o2) { return o2.getValue().compareTo(o1.getValue()); } }); for (Map.Entry<Character, Integer> entry : list) { sum += entry.getValue() * (26 - j); j++; } return sum; } }