题解 | #字符串价值#

字符串价值

https://www.nowcoder.com/practice/9f0db60f566c470a91e37162afc52b9c

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        int[] a = new int[s.length()];
        int sum = 0;
        int index = 0;
        int k = sc.nextInt();
        HashMap<Character,Integer> map = new HashMap<>();
        for(int i = 0;i<s.length();i++){
            char c = s.charAt(i);
            if(map.containsKey(c)){
                int v = map.get(c)+1;
                map.put(c,v);
                a[index] = 2*v - 1;
                sum+=a[index];
                index++;
            }else{
                map.put(c,1);
                a[index++] = 1;
                sum+=1;
            }
        }
        Arrays.sort(a);
        index = s.length() - 1;
        while(k>0){
            k--;
            sum -= a[index--];
        }
        System.out.println(sum);
    }
}

全部评论

相关推荐

“校招”、“3-5年经验”
xiaolihuam...:逆向工程不是搞外挂的吗,好像现在大学生坐牢最多的就是诈骗罪和非法侵入计算机系统罪,发美金,还居家办公,就是怕被一锅端,
点赞 评论 收藏
分享
头像 会员标识
05-26 10:24
门头沟学院 Java
qq乃乃好喝到咩噗茶:其实是对的,线上面试容易被人当野怪刷了
找工作时遇到的神仙HR
点赞 评论 收藏
分享
05-30 12:03
山西大学 C++
offer来了我跪着...:不是骗子,等到测评那一步就知道为啥这么高工资了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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