首页 > 试题广场 >

字符串价值

[编程题]字符串价值
  • 热度指数:296 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
有一种有趣的字符串价值计算方式:统计字符串中每种字符出现的次数,然后求所有字符次数的平方和作为字符串的价值
例如: 字符串"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
import java.util.Scanner;
public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int[] freq = new int[26];
    int i, k, s=0;
    String input = sc.nextLine();
    k = sc.nextInt();
    for (i=0; i<input.length(); ++i)
      freq[(int)(input.charAt(i)-'a')]++;
    while (k-- != 0) {
      i = maxElement(freq);
      freq[i]--;
    }
    for (i=0; i<26; ++i)
      s += freq[i]*freq[i];
    System.out.println(s);
  }
  private static int maxElement(int[] array) {
    int i, maxIndex=0;
    for (i=1; i<array.length; ++i)
      maxIndex = array[i]>array[maxIndex] ? i : maxIndex;
    return maxIndex;
  }
}

发表于 2018-03-17 23:32:45 回复(0)