題目描述
有一種有趣的字符串價值計算方式:統計字符串中每種字符出現的次數,然後求所有字符次數的平方和作爲字符串的價值
例如: 字符串"abacaba",裏面包括4個’a’,2個’b’,1個’c’,於是這個字符串的價值爲4 * 4 + 2 * 2 + 1 * 1 = 21
牛牛有一個字符串s,並且允許你從s中移除最多k個字符,你的目標是讓得到的字符串的價值最小。
輸入描述:
輸入包括兩行,第一行一個字符串s,字符串s的長度length(1 ≤ length ≤ 50),其中只包含小寫字母(‘a’-‘z’)。
第二行包含一個整數k(0 ≤ k ≤ length),即允許移除的字符個數。
輸出描述:
輸出一個整數,表示得到的最小价值
示例1
輸入
aba
1
輸出
2
package com.qiye;
import java.util.*;
public class ValueOfString {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
int n = scanner.nextInt();
char array[] = s.toCharArray();
/**
* 使用HashMap字典來統計每個字符出現的次數
*/
HashMap<Character,Integer> hashMap = new HashMap<>();
for(int i=0;i < array.length;i ++){
if(hashMap.containsKey(array[i])){
int weight = hashMap.get(array[i]);
hashMap.put(array[i],weight + 1);
}
else{
hashMap.put(array[i],1);
}
}
/**
* 構建一個數組,保存每個字符出現的次數
*/
int sum[] = new int[hashMap.size()];
int index = 0;
for(Map.Entry entry:hashMap.entrySet()){
sum[index] = (Integer)entry.getValue();
index ++;
}
// for(int i=0;i < sum.length;i ++){
// System.out.println(sum[i]);
// }
/**
* 每次都對統計數組排序,讓最大值減一
*/
while(n > 0){
Arrays.sort(sum);
sum[sum.length -1] --;
n--;
}
/**
* 對操作完成的數組中每一個值求和
*/
int result = 0;
for(int i=0;i < sum.length;i ++){
result += sum[i] * sum[i];
}
System.out.println(result);
}
}
注意
統計次數最好使用字典。