题解 | #名字的漂亮度#

名字的漂亮度

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

贪心

  • 选最多的字母为26,依次递减
  • 重写排序版
import java.util.*;
public class Main {
    public static void main(String []args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            String s = sc.next();
            HashMap<Character, Integer> map = new HashMap<>();
            ArrayList<Integer> list;
            for (int j = 0; j < s.length(); j++) {
                char c = s.charAt(j);
                if (map.containsKey(c)) {
                    map.put(c, map.get(c) + 1);
                } else {
                    map.put(c, 1);
                }
            }
            list = new ArrayList(map.values());
            Collections.sort(list, (a, b)-> {
                return b - a ;
            });
            //             或者是重写的这种格式
            //             new Comparator<ArrayList<Integer>>(){
            //                 @Override
            //                 public int compare(Integer a ,Integer b){
            //                     return b- a ;
            //                 }
            //             }
            int ans = 0;
            int count = 26;
            for (int num : list ) {

                ans += num * count;
                count--;
            }
            System.out.println(ans);
        }
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务