题解 | #字符串价值#

字符串价值

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);
    }
}

全部评论

相关推荐

沟头学院:无关比赛不要写,这样会显着你主次不分,比赛不要撒谎,有哪些就写那些,创新创业建议删除。技能特长可以适当夸大。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务