题目详情:
我们要给每个字母配一个1-26之间的整数,具体怎么分配由你决定,
但不同字母的完美度不同,而一个字符串的完美度等于它里面所有字母的完美度之和,
且不在乎字母大小写,也就是说字母F和f的完美度是一样的。
现在给定一个字符串,输出它的最大可能的完美度。
例如:dad,你可以将26分配给d,25分配给a,这样整个字符串最大可能的完美度为77。
思路:
遍历字符串,对出现的各个字母进行计数,对计数结果进行排序,出现次数多的完美度大。
Java实现:
public static int perfect(String s) {
int result = 0;
s = s.toLowerCase();
int[] count = new int[26];
for (int i = 0; i < s.length(); i++) {
count[s.charAt(i) - 'a']++;
}
int temp = 0;
// 将统计数组从大到小排序
for (int i = 0; i < 25; i++) {
for (int j = i + 1; j < 26; j++) {
if (count[j] > count[i]) {
temp = count[i];
count[i] = count[j];
count[j] = temp;
}
}
}
// 设定并计算完美度
for (int perfect = 26, i = 0; i < count.length; i++, perfect--) {
result += perfect * count[i];
}
return result;
}