厐果英雄会之字符串的完美度

原题地址如下:http://hero.pongo.cn/Question/Details?ID=71&ExamID=69

题目大意:

我们要给每个字母配一个1-26之间的整数,具体怎么分配由你决定,但不同字母的完美度不同,

而一个字符串的完美度等于它里面所有字母的完美度之和,且不在乎字母大小写,也就是说字母F和f的完美度是一样的。


现在给定一个字符串,输出它的最大可能的完美度。

例如:dad,你可以将26分配给d,25分配给a,这样整个字符串最大可能的完美度为77。


函数头部

C

int perfect(const char *s);

C++

int perfect(const string &s);

java

public static int perfect(String s);

 

我的代码如下:

 1 public class Test05 {
 2     private static HashMap<Character, Integer> map = new HashMap<Character, Integer>();
 3 
 4     public static void main(String[] args) {
 5         System.out
 6                 .println(perfect("aaAddcf"));
 7     }
 8 
 9     public static int perfect(String s) {
10         char[] chars = s.toLowerCase().toCharArray();
11         for (int i = 0; i < chars.length; i++) {
12             if (map.containsKey(chars[i])) {
13                 int value = map.get(chars[i]);
14                 map.put(chars[i], value + 1);
15             } else {
16                 map.put(chars[i], 1);
17             }
18         }
19         Collection<Integer> list = map.values();
20         System.out.println(list);
21         Object[] arrs = list.toArray();
22         Arrays.sort(arrs);
23         int key = 26;
24         int result = 0;
25         for (int i = arrs.length - 1; i >= 0; i--) {
26             result += key * (Integer) arrs[i];
27             key--;
28         }
29         map.clear();
30         return result;
31     }
32 
33 }

比较丢人的是前后提交了九次才通过,刚开始不知道问题在哪儿,自己电脑上运行没问题,已提交就是测试不通过,后来发现,是因为它后台的测试用例有两个,而我刚开始的代码里面没有第29行清空map的代码,导致第二次测试的时候结果加载了第一次测试的结果之上,当然不对了,而我自己只是测了一遍而已,当然找不到错了。

posted @ 2013-07-27 08:33  画水  阅读(377)  评论(0编辑  收藏  举报